JdbcConnection
package jdbc;
import org.junit.Test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcConnectionTest {
//获取连接方式一
@Test
public void getConncetion1() throws SQLException {
//1.提供java.sql.Driver接口实现类的对象
Driver driver = new com.mysql.jdbc.Driver();
//2.提供url,指明具体操作的数据
String url = "jdbc:mysql://localhost:3306/book";
//3.提供Properties的对象,指明用户名和密码
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//4.调用driver的connect(),获取连接
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
//获取连接方式二
@Test
public void getConncetion2() throws Exception{
//1.通过反射实例化Driver
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2.提供url,指明具体操作的数据
String url = "jdbc:mysql://localhost:3306/book";
//3.提供Properties的对象,指明用户名和密码
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//4.调用driver的connect(),获取连接
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
//获取连接方式三
@Test
public void getConncetion3() throws Exception{
//1.数据库连接的基本要素
//提供url,指明具体操作的数据库、登录用户和密码
String url = "jdbc:mysql://localhost:3306/book";
String user = "root";
String password= "123456";
//2.通过反射实例化Driver
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//3.注册驱动
DriverManager.registerDriver(driver);
//4.获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
//获取连接方式四
@Test
public void getConncetion4() throws Exception{
//1.数据库连接的基本要素
//提供url,指明具体操作的数据库、登录用户和密码
String url = "jdbc:mysql://localhost:3306/book";
String user = "root";
String password= "123456";
//2.通过反射实例化Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//3.获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
//获取连接方式五(推荐)
@Test
public void getConncetion5() throws Exception{
//1.加载配置文件
InputStream resource = JdbcConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resource);
//2.读取配置信息
String user = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClassName");
//3.加载驱动
Class.forName(driverClass);
//4.获取连接
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
}
}