在初学者练习和使用JDBC时,在代码中会反复连接数据库。从而出现严重的代码冗余,该文对JDBC代码进行简单的封装供大家使用。
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class MysqlConnection {
/**
定义getConnection()方法来获取Connection的对象,方便增删改查方法直接使用。
*/
private Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:????/"数据库名"?characterEncoding=UTF-8","Mysql账号", "Mysql密码");
return conn;
}
/**
增删改查功能,都是传入sql命令和sql命令中占位符的值。
*/
public static ResultSet MysqlSearch(String sql,String ... args) throws ClassNotFoundException, SQLException {
Connection conn=getConnection(); //获取conn对象
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql); //执行sql命令
for (int i=0;i<args.length;i++) { //利用循环给占位符赋值
ps.setString(i+1, args[i]);
}
ResultSet rs=ps.executeQuery();
return rs; //返回ResultSet类型的值
}
public static void MysqlAdd(String sql,String ... args) throws ClassNotFoundException, SQLException {
Connection conn=getConnection();
PreparedStatement ps2=(PreparedStatement) conn.prepareStatement(sql);
for (int i=0;i<args.length;i++) {
ps2.setString(i+1, args[i]);
}
ps2.executeUpdate();
}
public static void MysqlDel(String sql,String ... args) throws ClassNotFoundException, SQLException {
Connection conn=getConnection();
PreparedStatement ps2=(PreparedStatement) conn.prepareStatement(sql);
for (int i=0;i<args.length;i++) {
ps2.setString(i+1, args[i]);
}
ps2.executeUpdate();
}
public static void MysqlUpdate(String sql,String ... args) throws ClassNotFoundException, SQLException {
Connection conn=getConnection();
PreparedStatement ps2=(PreparedStatement) conn.prepareStatement(sql);
for (int i=0;i<args.length;i++) {
ps2.setString(i+1, args[i]);
}
ps2.executeUpdate();
}
}