Connect to mysql database using java _ MySQL

Source: Internet
Author: User
Java connection to mysql database bitsCN.com

I would like to share with you a java encapsulation class for connecting to the 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 ();
}
}
}

BitsCN.com
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.