在初学者练习和使用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 {
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;
}
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



