JDBC連接MySQL數據庫
阿新 • • 發佈:2017-05-21
code log 方法 多個 驅動程序 color str sta test
首先導入mysql的驅動jar包
1、第一種方法
public class Demo1 { //jdbc協議:數據庫子協議://主機:端口號/連接的數據庫 private String url = "jdbc:mysql://localhost:3306/test"; private String user = "root"; private String password = "root"; @Test public void test1(){ Driver driver = new com.mysql.jdbc.Driver(); Properties props= new Properties(); props.setProperty("user", user); props.setProperty("password", password); Connection conn = driver.connect(url, props); System.out.println(conn); } }
2、第二種方法
public class Demo2 { //jdbc協議:數據庫子協議://主機:端口號/連接的數據庫 privateString url = "jdbc:mysql://localhost:3306/test"; private String user = "root"; private String password = "root"; @Test public void test2(){ Driver driver = new com.mysql.jdbc.Driver(); //1、註冊驅動程序(可以註冊多個程序) DriverManager.registerDriver(driver);//2、連接到具體數據庫 Connection conn = DriverManager.getConnection(url,user,password); System.out.println(conn); } }
//分析Driver類的源碼這樣寫道
static {
try{
java.sql.DriverManager.registerDriver(new Driver());
}catch(SQLException e){
throw new RuntimeException("Can‘t register driver!");
}
}
//靜態代碼塊在加載類的時候就已經執行了,所以上面的代碼相當於註冊了兩次。改進方法二,得方法3
3、第三種方法
public class Demo3{ //jdbc協議:數據庫子協議://主機:端口號/連接的數據庫 private String url = "jdbc:mysql://localhost:3306/test"; private String user = "root"; private String password = "root"; @Test public void test3() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(url,user,password); System.out.println(conn); } }
JDBC連接MySQL數據庫