Encapsulation for connecting java to mysql database
Public class DB {
Static {
Try {
Class. forName ("com. mysql. jdbc. Driver ");
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
}
Private DB (){}
Public static Connection getConn (){
Connection conn = null;
Try {
Conn = DriverManager. getConnection ("jdbc: mysql: // localhost/mydatabase? "+" User = root & password = root ");
} Catch (SQLException e ){
E. printStackTrace ();
}
Return conn;
}
Public static void closeConn (Connection conn ){
Try {
If (conn! = Null ){
Conn. close ();
Conn = null;
}
} Catch (SQLException e ){
E. printStackTrace ();
}
}
Public static Statement getStmt (Connection conn ){
Statement stmt = null;
Try {
Stmt = conn. createStatement ();
} Catch (SQLException e ){
E. printStackTrace ();
}
Return stmt;
}
Public static void closeStmt (Statement stmt ){
Try {
If (stmt! = Null ){
Stmt. close ();
Stmt = null;
}
} Catch (SQLException e ){
E. printStackTrace ();
}
}
// Obtain pStmt Based on conn and SQL
Public static PreparedStatement getPStmt (Connection conn, String SQL ){
PreparedStatement pStmt = null;
Try {
PStmt = conn. prepareStatement (SQL );
} Catch (SQLException e ){
E. printStackTrace ();
}
Return pStmt;
}
// Obtain the result set based on stmt and SQL
Public static ResultSet executeQuery (Statement stmt, String SQL ){
ResultSet rs = null;
Try {
Rs = stmt.exe cuteQuery (SQL );
} Catch (SQLException e ){
E. printStackTrace ();
}
Return rs;
}
// Obtain the result set based on conn and SQL
Public static ResultSet executeQuery (Connection conn, String SQL ){
ResultSet rs = null;
Try {
Rs = conn.createstatement(cmd.exe cuteQuery (SQL );
} Catch (SQLException e ){
E. printStackTrace ();
}
Return rs;
}
Public static void closeResultSet (ResultSet rs ){
Try {
If (rs! = Null ){
Rs. close ();
Rs = null;
}
} Catch (SQLException e ){
E. printStackTrace ();
}
}
}