一、JDBC配置类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class Config {
private static String username;
private static String password;
private static String url;
private static String driverClass;
static{
Properties prop = new Properties();
try {
InputStream in = new FileInputStream("JavaDemo10/config/jdbc.properties");
prop.load(in);
username = prop.getProperty("username");
password = prop.getProperty("password");
url = prop.getProperty("url");
driverClass = prop.getProperty("driverClass");
if(driverClass != null && url != null && username != null && password != null){
Class.forName(driverClass);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException {
Connection con = null;
try{
con = DriverManager.getConnection(url,username,password);
}catch (Exception e){
e.printStackTrace();
}
return con;
}
public static void close(Connection con, Statement stat , ResultSet res) throws SQLException {
if(con != null){
con.close();
}
if (stat != null) {
stat.close();
}
if (res != null) {
res.close();
}
}
}
二、配置文件
driverClass = com.mysql.cj.jdbc.Driver
username = root
password = 123456
url = jdbc:mysql://localhost:3306/databaseName
三、通用工具类
import java.sql.*;
public class JdbcUtils {
private static Connection con = null;
private static Statement st = null;
private static ResultSet rs = null;
private static PreparedStatement ps = null;
public static int update(String sql,Object ...params) throws SQLException {
int flag = 0;
try {
con = Config.getConnection();
ps = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1,params[i]);
}
flag = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
Config.close(con,ps,null);
}
return flag;
}
public static ResultSet query(String sql,Object ...params) throws SQLException {
try {
con = Config.getConnection();
ps = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
}