原生jdbc 工具类
jabc.propertis文件放src下
在使用的地方声明成员变量,作用域高
Connection connection=null;
-
PreparedStatement preparedStatement =null;
-
ResultSet resultSet =null;
-
Statement statement=null;
代码
ackage utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 导包要导入Java.sql的包
* JDBC工具类的封装
* 工具类:提取重复代码
* 以下声明为成员变量。提高作用域
* Connection connection=null;
* PreparedStatement preparedStatement =null;
* ResultSet resultSet =null;
* Statement statement=null;
*/
public class JdbcUtils {
private static final String driver;
private static final String url;
private static final String username;
private static final String password;
//使用的时候在使用类声明这些
// Connection connection=null;
// PreparedStatement pstmt =null;
// ResultSet resultSet =null;
//1.导入jar包
//加载配置文件
static{
System.out.println("加载配置文件");
Properties properties = new Properties();
try {
//直接new InputStream()写相对路径一直出错
InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
//静态代码块:保证驱动只加载一次
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
//提升connection的作用域
Connection connection =null;
try {
connection = DriverManager.getConnection(url , username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 适用于 预编译的查询操作
* @param rs
* @param psmt
* @param conn
*/
public static void closeResource(ResultSet rs,PreparedStatement psmt,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (psmt!=null){
try {
psmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
psmt=null;
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
/**
* 适用于 预编译的 增删改操作
*
*/
public static void closeResource(PreparedStatement psmt,Connection conn){
if (psmt!=null){
try {
psmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
psmt=null;
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
小案例
@Override
public void up() throws SQLException {
connection = JdbcUtils.getConnection();
preparedStatement = connection.prepareStatement(“insert into student(id,name,password,gender) values(?,?,?,?)”);
preparedStatement.setInt(1,4);
preparedStatement.setString(2,“zhangsan”);
preparedStatement.setString(3,“79797”);
preparedStatement.setString(4,“nan”);
preparedStatement.executeUpdate();
JdbcUtils.closeResource(resultSet,preparedStatement,connection);
}