ç¨JDBCè¿æ¥æ°æ®åºï¼ç¶åç¨sqlè¯å¥ãè¦å¯¼å
¥mysqlç驱å¨å
ã
import java.sql.*;
public class TestMySql {
static Connection con = null; // 声æConnection对象
static Statement sql = null;
static ResultSet res = null;
public static void main(String[] args) {
TestMySql c = new TestMySql();
con = c.getConnection();
try {
sql = con.createStatement();
res = sql.executeQuery("select * from dept");
//sqlè¯å¥ï¼ææ°æ®åºéæå¼ dept表
while (res.next()) {//è¾åºç»æ
System.out.print(res.getString(1) + "<ââ>");
System.out.print(res.getString(2) + "<ââ>");
System.out.print(res.getString(3) );
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (res != null) {
res.close();
res =null;
}
if (sql != null) {
sql.close();
sql =null;
}
if (con != null) {
con.close();
con =null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
// å è½½oracleJDBC驱å¨
System.out.println("æ°æ®åºé©±å¨å è½½æå");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {// éè¿è®¿é®æ°æ®åºçURLè·åæ°æ®åºè¿æ¥å¯¹è±¡
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydata", "root", "qwer1234");
//mydata为mysqlåå
System.out.println("æ°æ®åºè¿æ¥æå");
} catch (SQLException e) {
e.printStackTrace();
}
return con; // ææ¹æ³è¦æ±è¿åä¸ä¸ªConnection对象
}
}
温馨提示:答案为网友推荐,仅供参考