JDBC database connection tool class
The following is the connection to the SQLServer database
If it is mysql, change the connection driver and connection path to:
// Connect to the driverprivate static final String DRIVER=""; // Connection pathprivate static final String URL ="jdbc:mysql://localhost:3306/XXX";
import .*; /** * Database connection tool class */ public class DataBaseConnectionUtil { // Connect to the driver private static final String DRIVER= ""; // Connection path private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=XXX"; // username private static final String USERNAME = "sa"; // password private static final String PASSWORD = "123456"; // Static code block static { try { // Load the driver (DRIVERCLASSNAME); } catch (ClassNotFoundException e) { (); } } /* * Get database connection */ public static Connection getConnection() { Connection conn = null; try{ conn= (URL, USERNAME, PASSWORD); }catch(SQLException e){ (); } return conn; } /* * Close the database connection and release the resources */ public static void close(ResultSet rs, PreparedStatement ps, Connection conn) { if(rs!=null){ try{ (); rs=null; }catch(SQLException e){ (); } } if(ps!=null){ try{ (); ps=null; }catch(SQLException e){ (); } } if(conn!=null){ try{ (); conn=null; }catch(SQLException e){ (); } } } /* * Close the database connection and release the resources */ public static void close2( PreparedStatement ps, Connection conn) { if(ps!=null){ try{ (); ps=null; }catch(SQLException e){ (); } } if(conn!=null){ try{ (); conn=null; }catch(SQLException e){ (); } } } }
Use it specifically in the class
public void AAA() { try { //Connect the database conn = (); String sql = "sqlStatement(Usually placeholders are left here? likeinsert into Test (A,B,C,D) values(?,?,?,?))"; ps = (sql); (1, A); (2, B); (3, C); (4, D); // Execute SQL statements (); } catch (SQLException e) { (); } finally { // Close the database connection object DataBaseConnectionUtil.close2(ps, conn); } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.