以mysql连接为例
引入驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<!--<scope>runtime</scope>-->
</dependency>
junit泰马
package xyz.hashdog.jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionTest {
/**
* 1.通过驱动实现类获取
* @throws SQLException
*/
@Test
public void testConnection1() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/st-jdbc";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","hashdog2019");
Connection conn = driver.connect(url,info);
System.out.println(conn);
}
/**
* 2.通过反射获取
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SQLException
*/
@Test
public void testConnection2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//反射方式获取Driver实现类,可以根据驱动包名切换
Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/st-jdbc";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","hashdog2019");
Connection conn = driver.connect(url,info);
System.out.println(conn);
}
/**
* 3.DriverManager替换Driver
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SQLException
*/
@Test
public void testConnection3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//1.获取Driver实现类
Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance();
//2.提供基本信息
String url = "jdbc:mysql://localhost:3306/st-jdbc";
String user = "root";
String password = "hashdog2019";
//3.注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
/**
* 4.优化方式三,加载驱动会自动注册
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SQLException
*/
@Test
public void testConnection4() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//1.提供基本信息
String url = "jdbc:mysql://localhost:3306/st-jdbc";
String user = "root";
String password = "hashdog2019";
//2.获取Driver实现类
Class.forName("com.mysql.jdbc.Driver");
// Driver driver = (Driver)clazz.newInstance();
// DriverManager.registerDriver(driver);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}