数据库的连接方式
数据库连接的四个要素
1、加载驱动Driver:加载 JDBC 驱动需调用 Class 类的静态方法 forName(),向其传递要加载的 JDBC 驱动的类名 2、统一资源定位符url:JDBC URL 用于标识一个被注册的驱动程序,驱动程序管理器通过这个 URL 选择正确的驱动程序,从而建立到数据库的连接。mysql的统一资源定位符为:jdbc:mysql://localhost:3306/数据库名 3、用户名:mysql的用户名一般为root 4、密码 四个基本要素可以写在jdbc.properties中,使用类的加载器加载读取,可提高代码的可移植性,解耦。 可以调用 DriverManager 类的 getConnection() 方法建立到数据库的连接
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class ConnectionTest {
@Test
public void testConnectionTest1() throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/bookmanager?characterEncoding=utf-8";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","124869");
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
@Test
public void testConnection2() throws Exception {
Class class1 = Class.forName("com.mysql.jdbc.Driver");
Driver driver =(Driver) class1.newInstance();
String url = "jdbc:mysql://localhost:3306/bookmanager?characterEncoding=utf-8";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","124869");
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
@Test
public void testConnection3() throws Exception {
String url = "jdbc:mysql://localhost:3306/bookmanager?characterEncoding=utf-8";
String user = "root";
String password = "124869";
Class class1 = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)class1.newInstance();
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
@Test
public void testConnection4() throws Exception {
String url = "jdbc:mysql://localhost:3306/bookmanager?characterEncoding=utf-8";
String user = "root";
String password = "124869";
Class class1 = Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
@Test
public void testConnection5() throws Exception {
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");
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
下面描述的getResourceAsStream的用法和解释
https://www.cnblogs.com/macwhirr/p/8116583.html
|