Package COM.CN.JDBC;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
Public class Jdbc_connection {
//Load driver, link database
public static Connection getconnection () throws SQLException,
classnotfoundexception{
Class.forName ("Com.mysql.jdbc.Driver");
String url= "Jdbc:mysql://localhost:3306/rentbikes";
String username= "root";
String password= "000000";
Connection conn=drivermanager.getconnection (URL, username, password);
Return conn;
}
//Close database connection, free resources
public static void release (Statement stmt,connection conn) {
if (stmt!=null) {
try{
Stmt.close ();
}catch (SQLException e) {
E.printstacktrace ();
}
Stmt=null;
}
if (conn!=null) {
try{
Conn.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
Conn=null;
}
}
public static void release (ResultSet rs,statement stmt,connection conn) {
if (rs!=null) {
try{
Rs.close ();
}catch (SQLException e) {
E.printstacktrace ();
}
Rs=null;
}
Release (Stmt,conn);
}
}
Summary: Because each time the database is operational, it is necessary to load the database driver, establish a database connection and close the database connection, this tool class can avoid the duplication of code writing.
Encapsulates a tool class to enable JDBC to connect to a MySQL database