-
“获得数据库连接”操作,将在以后的增删改查所有功能中都存在,
可以封装工具类JDBCUtils
。提供获取连接对象的方法,从而达到代码的重复利用。
-
该工具类提供方法:public static Connection getConnection()。代码如下:
jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day0204_db
jdbc.username=root
jdbc.password=root
通过Properties 读取配置文件内容
@Test
public void demo06() throws Exception {
// 需求6: 读取配置文件内容
// 1 创建对象
Properties props = new Properties();
// 2 加载文件
InputStream in = JDBCTest.class.getClassLoader().getResourceAsStream(“jdbc.properties”);
props.load(in);
// 3 读取内容 且 打印
String url = props.getProperty(“jdbc.url”);
String username = props.getProperty(“jdbc.username”);
System.out.println(url);
System.out.println(username);
}
JDBC工具类
package cn.hanjiaxiaozhi.utils;
import cn.hanjiaxiaozhi.JDBCTest;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String driverClassName;
private static String url;
private static String username;
private static String password;
static {
try {
// 1 创建对象
Properties props = new Properties();
// 2 加载文件
InputStream in = JDBCTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
props.load(in);
// 3 读取内容 且 打印
driverClassName = props.getProperty("jdbc.driverClassName");
url = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
password = props.getProperty("jdbc.password");
// 1 注册驱动
Class.forName(driverClassName);
} catch (Exception e) {
e.printStackTrace();
}
}
// 1 获取连接
public static Connection getConnection() throws SQLException {
// 2 获取连接
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
// 2 释放资源
public static void release(Connection conn, Statement stmt, ResultSet rs) {
try {
if(rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
release(conn, stmt);
}
public static void release(Connection conn, Statement stmt) {
try {
if(stmt!=null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用JDBC工具类 完成查询
@Test
public void demo01() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 2 获取连接
conn = JDBCUtils.getConnection();
// 3 获取执行sql对象
String sql = "select * from tb_user";
stmt = conn.prepareStatement(sql);
// 4 执行sql 获取结果
rs = stmt.executeQuery();
// 5 处理结果
while (rs.next()) {
int uid = rs.getInt("uid");
String uname = rs.getString("username");
String upwd = rs.getString("password");
String nickname = rs.getString("nickname");
System.out.println(uid +"============="+ uname +"============="+ upwd +"============="+ nickname);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6 释放资源
JDBCUtils.release(conn, stmt, rs);
}
}