java操作数据库, 如果不进行整合, 添加,删除,修改,查询等操作将会有太多的重复代码出现, 操作不易, 同时也影响美观, 因此,将重复的代码进行整合,形成一个类, 然后调用就会简单很多
package yteng;
//先在lib下引入包mysql-connector-java-5.1.39-bin.jar
import java.sql.*;
public class Db {
// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/stu_info";
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
//static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://localhost:3306/stu_info?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "root";
public static Connection conn = null;
public static PreparedStatement ps = null;
public static ResultSet rs = null;
static {
try {
//加载驱动
Class.forName(DRIVER); //将mysql驱动注册到DriverManager中去
//Class.forName 方法的作用,就是初始化给定的类
} catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
//得到数据库连接对象
public static Connection conn() {
if(conn == null){
//获取连接
try {
conn = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (SQLException e) {
e.printStackTrace();
}
//返回一个数据库连接对象, 通过个对象就可以对数据库进行增删除改查操作了
}
return conn;
}
//基本的增,删,改操作
public static int exec(String sql, Object...args) {
conn = conn();
int count = 0;
try {
//prepareStatement对象防止sql注入的方式是把用户非法输入的单引号用\反斜杠做了转义,从而达到了防止sql注入的目的
ps = conn.prepareStatement(sql);
//设置占位符参数
if(args != null) {
for(int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
}
count = ps.executeUpdate();
//设置占位符参数
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return count;
}
//返回新增加数据的id
public static int lastInsertId(String sql, Object...args) {
conn = conn();
int id = -1;
try {
//prepareStatement对象防止sql注入的方式是把用户非法输入的单引号用\反斜杠做了转义,从而达到了防止sql注入的目的
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
//设置占位符参数
if(args != null) {
for(int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
}
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if(rs.next())
{
id = rs.getInt(1);
}
//设置占位符参数
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return id;
}
//查询操作
public static ResultSet fetch(String sql, Object...args) {
conn = conn();
try {
ps = conn.prepareStatement(sql);
//设置占位符参数
if(args != null) {
for(int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
}
rs = ps.executeQuery(); //返回 查询的数据结果
//设置占位符参数
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
return rs;
}
public static void close() {
try {
if(rs != null) {rs.close(); rs = null;}
if(ps != null) {ps.close(); ps = null;}
if(conn != null) {conn.close(); conn = null;}
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
}Db.java下载
