package com.csy.jdbc.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
//定义相关的属性,因为只需要一份,因此选择static
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");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
//在实际开发中,我们可以这样处理
//1将编译异常转换成运行异常
//2这样使调用者 可以选择捕获该异常,也可以选择默认处理该异常,比较方便。
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){
//判断是否为空
try {
if (set != null){
set.close();
}
if (statement !=null){
statement.close();
}
if (connection != null){
connection.close();
}
}catch (SQLException e){
//将编译异常转换成运行时异常
throw new RuntimeException(e);
}
}
}
这里有个可能出现的坑:如果是用idea的话,用getResourceAsStream方法读取配置文件默认是在src下读的,而用FileInputStream读取的话分两种情况:在单元测试中,默认是在module下读的,而在main方法中,默认是在project下读的,这个要小心
比如说,如果把配置文件放在src下,用getResourceAsStream的话直接写文件名,在单元测试中用FileInputStream,需要写 src\\文件名,在main方法中用FileInputStream,需要写 module名\\src\\文件名
JDBCUtils 的使用实例 dml操作
@Test
public void testDML(){
// update
//1 得到连接
Connection connection = null;
//2 组织一个sql
String sql = "update actor set name = ? where id = ?";
PreparedStatement preparedStatement = null;
// 创建一个PreparedStatement对象
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//给占位符赋值
preparedStatement.setString(1,"bbb");
preparedStatement.setInt(2,1);
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
}
查询操作
@Test
public void testSelect(){
//select
//1 第一步获取连接
Connection connection = null;
//2 组织一个sql
String sql = "select * from admin ";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
//3 创建一个PreparedStatement
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String pwd = resultSet.getString("pwd");
System.out.println( id + name + pwd);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(resultSet,preparedStatement,connection);
}
}