
介绍:在jdbc操作中,获取连接和释放资源,是经常使用到的,将其作为工具类封装到JDBCUtils中。
package com.jh.jdbc;
//该类是一个工具类,完成mysql的连接和关闭资源
import java.io.FileInputStream; import java.io.IOException; import java.sql.*; import java.util.Properties;
public class JDBCUtils {
//定义相关的属性,将属性做成静态属性
private static String user;//用户名
private static String password;//密码
private static String url;//
private static String driver;//驱动名
//在static代码块中初始化
static{
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//读取相关的属性
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} catch (IOException e) {
//在开发中使用编译异常,因为使用者,可以选择捕获异常也可以选择处理该异常,较方便
throw new RuntimeException(e);
}
}
//连接数据库,返回Connection
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//关闭资源
/*
*1.ResultSet 结果集
*2.Statement 或 PreparedStatement
*3.Connection
*4.如果关闭资源,传入对象,否则传入null
* */
public static void close(ResultSet set, Statement statement,Connection connection){
//判断是否为null
try {
if(set != null){
set.close();
}
if (statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
}catch (SQLException e){
throw new RuntimeException(e);
}
}
}
@Test
public void testDML(){//
//1.得到连接
Connection connection = JDBCUtils.getConnection();
//2.组织SQL语句
String sql = "update jh_db02 set name = ? where id = ?";
PreparedStatement preparedStatement = null;
//3.创建PreparedStatement对象
try {
preparedStatement = connection.prepareStatement(sql);
//给占位符赋值
preparedStatement.setString(1,"jason");
preparedStatement.setInt(2,1);
//执行
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
}

@Test
public void testSelect(){
//1.得到连接
Connection connection = JDBCUtils.getConnection();
//2.组织SQL语句
String sql = "select * from jh_db02";
PreparedStatement preparedStatement = null;
ResultSet set = null;
//3.创建PreparedStatement对象
try {
preparedStatement = connection.prepareStatement(sql);
//执行得到结果集
set = preparedStatement.executeQuery();
//遍历得到结果集
while (set.next()){
int id = set.getInt("id");
String name = set.getString("name");
Date borndate = set.getDate("borndate");
//String passwd = set.getString("passwd");
System.out.println(id + " " + name + " " + borndate + " " );
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {//关闭资源
JDBCUtils.close(set,preparedStatement,connection);
}
}
