標籤:sys demo1 nec catch ring new out lex word
首先匯入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協議:資料庫子協議://主機:連接埠號碼/串連的資料庫 private String 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資料庫