Mysql数据库应用中简单的封装
public class DB {
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bbs", "root" , "root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static Statement createStmt(Connection conn) {
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
public static ResultSet executeQuery(Statement stmt, String sql) {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static int executeUpdate(Connection conn, String sql) {
int ret = 0;
Statement stmt = null;
try {
stmt = conn.createStatement();
ret = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(stmt);
}
return ret;
}
public static PreparedStatement preStmt(Connection conn,String sql)
{
PreparedStatement preStmt = null;
try
{
preStmt = conn.prepareStatement(sql);
} catch (SQLException e)
{
e.printStackTrace();
}
return preStmt;
}
public static PreparedStatement preStmt(Connection conn,String sql,int autoGenerateKeys )
{
PreparedStatement preStmt = null;
&n