JDBC操作中
无非就是
1.连接2.sql语句3.关闭
其中连接的关闭的语句如果是同一个数据库其实都是相同的
所以连接和关闭可以封装连接的释放来做一个工具类
进行更方便的调用
示例图
工具类代码
package yuan.hsp.JDBC;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
@SuppressWarnings("all")
//实现连接和关闭的JDBC工具类
public class JDBCUtils {
//定义相关属性,因为只需要一份用static修饰
private static String user;
private static String password;
private static String url;
private static String driver;
//用static初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\pra.properties"));
user=properties.getProperty("user");
user=properties.getProperty("password");
user=properties.getProperty("url");
user=properties.getProperty("driver");
} catch (IOException e) {//捕获异常
throw new RuntimeException(e);//实际开发中一般转为一个运行异常抛出去
//将编译异常转为运行异常,可以捕获或者默认处理
}
}
//获取连接
public static java.sql.Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new RuntimeException(e);//还是转运行异常
}
}
//关闭资源
//参数为可能需要关闭的资源
public static void close(ResultSet set,Statement statement,Connection connection) throws SQLException {
//参数用Statement既可以接收Statement也可以接收PreparedStatement
//判断是否为null,比如可能不是查询就没有ResultSet这个传入null即可,然后不等于null就关闭
if (set!=null)
set.close();
if (statement!=null)
statement.close();
if(connection!=null)
connection.close();
}
}
工具类写完了肯定要看看能不能用,接下来就是使用环节
查询的话步骤差不多这里就不说了
package yuan.hsp.JDBC.jdbcutils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
@SuppressWarnings("all")
//演示JDBC工具类使用
public class dml {
@Test
public void testDML() throws SQLException {
Connection connection = null;
//先组织sql语句
String sql="update actor set name= ? where id = ? ";
PreparedStatement prepareStatement=null;
try {
connection=JDBCUtils.getConnection();
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, "周星驰");
prepareStatement.setInt(2, 4);
prepareStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
JDBCUtils.close(null, prepareStatement, connection);
}
}
}