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 {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/book";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
@Test
public void getConncetion2() throws Exception{
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/book";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
@Test
public void getConncetion3() throws Exception{
String url = "jdbc:mysql://localhost:3306/book";
String user = "root";
String password= "123456";
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
@Test
public void getConncetion4() throws Exception{
String url = "jdbc:mysql://localhost:3306/book";
String user = "root";
String password= "123456";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
@Test
public void getConncetion5() throws Exception{
InputStream resource = JdbcConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resource);
String user = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClassName");
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
}
}