1.Driver接口实现类
1.1 Driver接口
- java.sql.Driver 接口是所有JDBC驱动程序要实现的接口
- 由驱动程序管理器类(java.sql.DriverManager)去调用,实现Driver
- MySQL的驱动:com.mysql.jdbc.Driver
1.2 加载注册驱动
- 加载驱动:需要调用Class的静态方法forName,传递需要加载的类名
- Class.forName(“com.mysql.jdbc.Driver”) - 注册驱动:DriverManager是驱动程序管理器类
- DriverManager.registerDriver(com.mysql.jdbc.Driver)来注册驱动
2.URL
-
JDBC的URL用于标识一个被注册的驱动程序,通过URL选择正确的驱动程序,建立数据库的连接
-
jdbc:mysql://localhost:3306/test
- 结构:jdbc:子协议:子名称
- 协议:JDBC URL中的协议总是jdbc
- 子协议:用于标识一个数据库驱动程序
- 子名称:标识数据库的方法,定位数据库,包括主机名,端口号,数据库名 -
JDBC程序与服务器端的字符集不一致,会导致乱码,通过参数指定服务器端的字符集
- jdbc:mysql://localhost:3306/test ?useUnicode=true&characterEncoding=utf8
3.用户名和密码
- 向数据库指明用户名和密码
- 可以调用DriverManager类的getConnection()方法创建与数据库的连接
4.数据库连接(代码)
public static void test05() throws Exception {
//1.获取配置文件中的信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties ps = new Properties();
ps.load(is);
String user=ps.getProperty("user");
String password=ps.getProperty("password");
String url=ps.getProperty("url");
String driverClass=ps.getProperty("driver");
//2.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取连接
Connection conn=DriverManager.getConnection(url,user,password);
System.out.println("conn = " + conn);
}
- 配置文件jdbc.properties
user=root
password=123456gh
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
driverClass=com.mysql.jdbc.Driver
5.封装数据库连接(代码)
- DBUtil.java
public static Connection getConnection() throws Exception {
//1.获取配置文件中的信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties ps = new Properties();
ps.load(is);
String user=ps.getProperty("user");
String password=ps.getProperty("password");
String url=ps.getProperty("url");
String driverClass=ps.getProperty("driver");
//2.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取连接
Connection conn= DriverManager.getConnection(url,user,password);
return conn;
}
public static void closeResource(Connection conn, Statement st){
try {
if(conn!=null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try {
if(st!=null){
st.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static void closeResource(Connection conn, Statement st, ResultSet rs){
try {
if(conn!=null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try {
if(st!=null){
st.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try {
if(rs!=null){
rs.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}