如下
package com.jdbc.connection; 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 ConnectionTest { //方式一 @Test public void testConnection1() throws SQLException { Driver driver = new com.mysql.jdbc.Driver();//获取Driver的实现类对象 String url = "jdbc:mysql://localhost:3306/bookdb"; Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password",""); Connection conn = driver.connect(url, info); System.out.println(conn); } //方式二:对方式一迭代 @Test public void testConnection2() throws Exception { //获取Driver的实现类对象(使用反射) Class clazz = Class.forName("com.mysql.jdbc.Driver()"); Driver driver = (Driver) clazz.newInstance(); //要链接的数据库 String url = "jdbc:mysql://localhost:3306/bookdb"; //获取需要的用户名和密码 Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password",""); //获取连接 Connection conn = driver.connect(url, info); System.out.println(conn); } //方式三:使用DriverManager替代Driver @Test public void testConnection3() throws Exception { //获取Driver的实现类对象(使用反射) Class clazz = Class.forName("com.mysql.jdbc.Driver()"); Driver driver = (Driver) clazz.newInstance(); //提供连接的基本信息 String url = "jdbc:mysql://localhost:3306/bookdb"; String user = "root"; String password = ""; //注册驱动 DriverManager.registerDriver(driver); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } @Test public void testConnection4() throws Exception { //提供连接的基本信息 String url = "jdbc:mysql://localhost:3306/bookdb"; String user = "root"; String password = ""; //加载Driver Class.forName("com.mysql.jdbc.Driver()"); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); System.out.println(conn); } //方式五:将数据库连接需要的4个基本信息声明在配置文件中 @Test public void testConnection5() throws Exception { //1.获取配置文件中4个基本信息 InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); //2.加载驱动 Class.forName(driverClass); //3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } }