package com.hspedu.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @author: guorui fu
* @versiion: 1.0
*/
public class JDBCUtils {
private static String user;
private static String password;
private static String url;
private static String driver;
static{
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\mysql.properties"));
} catch (IOException e) {
//转换成运行异常,调用者可以捕获这个异常,或默认处理
throw new RuntimeException(e);
}
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,user,password);
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
}
public static void close(ResultSet resultSet, Connection connection, Statement statement){
try {
if (resultSet != null){
resultSet.close();
}
if (connection != null){
connection.close();
}
if (statement != null){
statement.close();
}
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
}
}
package com.hspedu.jdbc;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author: guorui fu
* @versiion: 1.0
*/
public class JDBCUtils_use {
@Test
public void util_test(){
//在try-catch外声明,方便关闭调用
Connection connection = null;
PreparedStatement preparedStatement = null;
//sql语句
String sql = "delete from actor where `name` = '刘德华'";
try {
//建立连接
connection = JDBCUtils.getConnection();
//预处理
preparedStatement = connection.prepareStatement(sql);
//执行
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
} finally {
//关闭资源
JDBCUtils.close(null,connection,preparedStatement);
}
}
}