package Util;
import java.sql.*;
/**
* @author: zyd
* @date: 2022/8/20 12:51
*/
public class JDBCUtil {
public static final String URL="jdbc:mysql://127.0.0.1:3306/z_stugl?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
public static final String USER="root";
public static final String PASSWORD="123456";
private static Connection c;
private static PreparedStatement p;
public static int update (String sql, Object[] paramter) throws SQLException, ClassNotFoundException {
p=getConnection().prepareStatement(sql);
for (int i = 0; i <paramter.length; i++) {
p.setObject(i+1, paramter[i]);
}
int n=p.executeUpdate();
return n;
}
public static ResultSet select(String sql) throws SQLException, ClassNotFoundException {
p=getConnection().prepareStatement(sql);
ResultSet rs=p.executeQuery();
return rs;
}
public static ResultSet select(String sql,Object[] paramter) throws SQLException, ClassNotFoundException {
p=getConnection().prepareStatement(sql);
for (int i = 0; i < paramter.length; i++) {
p.setObject(i+1,paramter[i]);
}
ResultSet rs= p.executeQuery();
return rs;
}
public static void close(Connection c,PreparedStatement p) throws SQLException {
p.close();
c.close();
}
public static void close(ResultSet rs) throws SQLException {
close(c,p);
rs.close();
}
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
return c= DriverManager.getConnection(URL,USER,PASSWORD);
}
}
主要原理,看api Connection类,里面铺简单的路(createStatement)容易被sql注入,就创建一条安全的路(prepareStatement),?占位符绝绝子;url加时区和编码的是8以上的jdbc用的,8以下记得删除哦