天天看點

JDBC 連接配接Mysql(筆記)

JDBC 連接配接Mysql

方法一

@Test
public void testConnection1() throws Exception{
    //建立驅動
    Driver driver = new com.mysqk.jdbc.Driver();
    //jdbc:mysql:協定
    //localhost:ip位址
    //3306:預設mysql的端口号
    //test:test資料庫
    String url ="jdbc:mysql://localhost:3306/test";
    //将使用者名和密碼封裝在Properties中
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","1234");

    Connection conn =drive.connect(url,info);
    System.out.println(conn);
}
           

方法二

—對方法一的疊代:在如下的程式中不出現第三方的api,使程式具有更好的可移植性

@Test
public void testConnection2() throws Exception{
	//1.擷取Driver實作類對象,使用反射
    Class clazz = Class.forName("com.mysql.jdbc.Driver");
	Driver driver=(Driver)clazz.newInstance();
	//2.提供要連接配接的資料庫
	String url ="jdbc:mysql://localhost:3306/test";
    //3.将使用者名和密碼封裝在Properties中
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","1234");
	//4.擷取連接配接
    Connection conn =driver.connect(url,info);
    System.out.println(conn);
}
           

方式三

使用DriverManager替換Driver

@Test
public void testConnection3() throws Exception{
	//1.擷取Driver實作類對象,使用反射
    Class clazz = Class.forName("com.mysql.jdbc.Driver");
	Driver driver=(Driver)clazz.newInstance();
	//2.提供三個基本資訊
	String url="jdbc:mysql://localhost:3306/test";
	String user="root";
	String password="1234";
	//注冊驅動
	DriverManager.registerDriver(driver);
	
	//獲得連接配接
	Connection conn=DriverMangaer.getConnection(url,user,password);
	System.out.println(conn);
}
           

方法四

可以隻是加載驅動,驅動自動注冊過了。

@Test
public void testConnection3() throws Exception{
	//1.提供三個基本資訊
	String url="jdbc:mysql://localhost:3306/test";
	String user="root";
	String password="1234";
	//2.加載Driver
    Class.forName("com.mysql.jdbc.Driver");
	//在mysql的Driver實作類中,聲明了如下操作:
//static{
//		try{
//			java.sql.DriverManager.registerDriver(new 	Driver());
//		}catch{
//			throw new RuntimeException("Can't register driver!");
//		}
//	}
	
	//獲得連接配接
	Connection conn=DriverMangaer.getConnection(url,user,password);
	System.out.println(conn);
}