JDBC模板
使用方法:
1.在项目的resources文件里添加data.properties文件,内容为
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf-8
user=用户名
password=密码
2.项目采取单例模式,getStatement方法获取查询sql操作对象
3.getPreparedStatement方法获取增删改操作对象,预操作防止sql注入
4.使用完之后建议调用closeConnection方法关闭链接。
//
// Created by bianys on 2022/12/20.
// author: bianys
//
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {
private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Properties p = new Properties();
private static FileInputStream fis= null;
//单例模式
static {
try {
Path path = Paths.get("src/main/resources/data.properties");
fis = new FileInputStream(path.toAbsolutePath().toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
p.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
String driver=p.getProperty("driver");
String user=p.getProperty("user");
String url=p.getProperty("url");
String password=p.getProperty("password");
//1.注册驱动
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
try {
Class.forName(driver);
//2.获取连接
conn= DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static Statement getStatement(){
try
{
//3.创建数据库操作对象
return conn.createStatement();
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
public static PreparedStatement getPreparedStatement(String sql){
try
{
//3.创建数据库操作对象
return conn.prepareStatement(sql);
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
public static void closeConnection(){
if (stmt!=null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (ps!=null)
{
try
{
ps.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (conn!=null)
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (rs!=null)
{
try
{
rs.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}