Six steps of jdbc connection to database and handwritten implementation of simple database connection pool

Posted by Diggler on Wed, 24 Nov 2021 03:09:42 +0100

We may often use Hibernate, Mybatis, jpa and other frameworks in our study and work. These frameworks have a good encapsulation of the database connection pool and may ignore the underlying implementation of the database. Today, let's take a look at how to write a simple database connection pool. Before that, let's recall the steps of java connecting to the database:

  1. Register and load jdbc database driver
    First, load the driver into memory; Second. Take the initiative to register the currently loaded driver with DriverManager, which is the only Java class in the JDBC specification.
    Code embodiment:
         
    1. Class.forName(DriverName)
    2. //Where DriverName=Driver package name.
    3. //DriverName = "oracle.jdbc.driver.OracleDriver" of Oracle.
    4. //MySql DriverName = "com.mysql.jdbc.Driver";

     
  2. Get the Connection object Connection
     
         
    1. /*To connect to the database, you need to request and obtain the Connection object from java.sql.DriverManager, which represents the Connection of a database.
    2. Use the getconnection (string URL, string username, string password) method of DriverManager to pass in the path of the specified database to be connected, the username and password of the database.
    3. For example: / / connect to the MySql database. Both username and password are root
    4. */
    5. String url = "jdbc:mysql://localhost:3306/test";
    6. String username = "root";
    7. String password = "root" ;
    8. try{
    9. Connection con =DriverManager.getConnection(url ,username , password ) ;
    10. } catch(SQLException se){
    11. System.out.println( "Database connection failed!");
    12. se.printStackTrace();
    13. }
    14. /*1,DriverManager In the JDBC specification, it is a class rather than an interface. It is a service class used to manage JDBC drivers and provide getConnection() Method to establish the connection between the application and the database. When the jdbc driver is loaded into memory, it will actively register with the DriverManager. This line of code sends a connection request, and the DriverManager class will use the registered jdbc driver to create a connection to the database.
    15. 2,DriverManager.getConnection()Is a static method.
    16. 3,DriverManager In the java.sql package, when we call any method of any class (including interface) in the SQL package, a compile time exception SQLException will be reported. Here, we use a try block followed by multiple catch blocks to solve the problem.
    17. 4,Method parameter URL: uniform resource locator. Which host is the database we are connected to (this is determined by ip address) , the host may have several database software installed, such as sqlserver, mysql and oracle. The port number is also called the service number listening number. Sqlserver is 1433, mysql is 3306 and oracle is 1521:. The following table lists the URL writing methods of commonly used database software:
    18. Oracle: jdbc:oracle:thin:@ip:1521:dbName;
    19. MySql: jdbc:mysql://ip:3306:dbName;
    20. SQLServer: jdbc:sqlserver://ip:1443;databaseName=dbName;
    21. 5,When using the local ip address to connect, you need to turn off the firewall. Otherwise, you can't connect. If you use localhost or 127.0.0.1, you don't need to turn off the firewall.
    22. */

     
  3. Create Statement object
         
    1. /*1,Run a static SQL Statement. Usually implemented through a Statement instance.
    2. 2,Run dynamic SQL statements. Usually implemented through PreparedStatement instances.
    3. 3,Run a database stored procedure. Usually implemented through a CallableStatement instance.*/
    4. //Detailed implementation: sql injection cannot be prevented
    5. Statement stmt = con.createStatement();
    6. //Can prevent sql injection
    7. PreparedStatement pstmt=con.prepareStatement(sql);
    8. CallableStatement cstmt =con.prepareCall( "{CALLdemoSp(? , ?
    9. )}") ;

     
  4. Write and execute sql statements
     

         
    1. /*Statement Interface provides three methods to run SQL statements: executeQuery, executeUpdate, and execute
    2. 1,ResultSet executeQuery(String sql): Runs an SQL statement that queries the database. Returns a ResultSet object.
    3. 2,int executeUpdate(String sql): It is used to run INSERT, UPDATE or DELETE statements and SQL DDL statements, such as create table and DROP TABLE
    4. 3,execute(sql):Used to run statements that return multiple result sets, multiple update counts, or a combination of both.*/
    5. //Detailed implementation code:
    6. ResultSet rs = stmt.executeQuery( "SELECT * FROM ...") ;
    7. int rows = stmt.executeUpdate( "INSERTINTO ...") ;
    8. boolean flag =stmt.execute(String sql) ;

     

  5. There are two cases of processing results:
     

         
    1. /* 1,Running update returns the number of records affected by this operation.
    2. 2,The result returned by running the query is a ResultSet object.
    3. ResultSet It includes all rows that meet the conditions in the SQL statement, and it provides access to the data in these rows through a set of get methods.*/
    4. //Get data using the access method of the ResultSet object:
    5. while(rs.next()){
    6. String name = rs.getString( "name") ;
    7. String pass = rs.getString( 1) ; // This method is more efficient
    8. }
    9. (Columns are numbered from left to right, and 1 (start)

     

  6. Close resource release resource

     

         
    1. /*After the operation is completed, close all the JDBC objects used to release JDBC resources. The closing order is opposite to the declaration order:
    2. 1,Close Recordset
    3. 2,Close declaration
    4. 3,Close connection object
    5. */
    6. if(rs != null){ // Close Recordset
    7. try{
    8. rs.close() ;
    9. } catch(SQLException e){
    10. e.printStackTrace() ;
    11. }
    12. }
    13. if(stmt != null){ // Close declaration
    14. try{
    15. stmt.close() ;
    16. } catch(SQLException e){
    17. e.printStackTrace() ;
    18. }
    19. }
    20. if(conn != null){ // Close connection object
    21. try{
    22. conn.close() ;
    23. } catch(SQLException e){
    24. e.printStackTrace() ;
    25. }
    26. }



    Every time the client accesses the database, the database returns the client data, accompanied by the creation and destruction of a connection. The main purpose of introducing connection pool is to improve performance,   Because creating a new JDBC connection will lead to networking operations and certain jdbc driver overhead, followed by reducing resource overhead.

    When a thread needs to use JDBC to perform operations on MySQL or other databases, it needs to use the connection provided by the connection pool. After using the connection to complete the thread, the thread will return the connection to the connection pool so that the connection can be used by other threads that need to use the connection. Borrow from the connection pool When connecting, the connection is only used by the thread requesting it. From a programming point of view, its effect is equivalent to calling DriverManager.getConnection() every time a JDBC connection is required. However, using connection pooling technology, the thread can be ended by using a new or existing connection. Connection pooling technology can significantly increase the performance of Java applications and reduce resource utilization.

    The mainstream connection pools on the market include c3p0, dbcp, druid, Tomcat JDBC, hikaricp (springboot 2.0 default connection pool), proxool, etc

    Here is a simple database connection pool:
    The connection pool is actually a container. Multiple threads may acquire and release connections at a certain time, so thread safety needs to be guaranteed


     

         
    1. package cn.itcats.thread.datasoursepool;
    2. /**
    3. * Custom database connection pool
    4. * @author fatah
    5. */
    6. import java.sql.Connection;
    7. import java.sql.DriverManager;
    8. import java.sql.SQLException;
    9. import java.util.LinkedList;
    10. import java.util.concurrent.locks.Condition;
    11. import java.util.concurrent.locks.Lock;
    12. import java.util.concurrent.locks.ReentrantLock;
    13. public class MyDataSourcePool {
    14. // Use container - there are few use environment query criteria, mainly for adding, deleting and modifying operations
    15. private LinkedList<Connection> pool = new LinkedList<>();
    16. private static final int INIT_CONNECTIONS = 10;
    17. private static final String DRIVER_CLASS = "";
    18. private static final String USERNAME = "";
    19. private static final String PASSWORD = "";
    20. private static final String URL = "";
    21. private Lock lock = new ReentrantLock();
    22. private Condition condition = lock.newCondition();
    23. static {
    24. // Register driver
    25. try {
    26. Class.forName( "com.mysql.jdbc.Driver");
    27. } catch (ClassNotFoundException e) {
    28. e.printStackTrace();
    29. }
    30. }
    31. // Initialize the connection through the construction method
    32. public MyDataSourcePool() {
    33. for ( int i = 0; i < INIT_CONNECTIONS; i++) {
    34. try {
    35. Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    36. pool.addLast(conn);
    37. } catch (SQLException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. }
    42. // Get database connection
    43. public Connection getConnection() {
    44. Connection conn = null;
    45. lock.lock();
    46. try {
    47. while (pool.size() < 0) {
    48. try {
    49. condition.await();
    50. } catch (InterruptedException e) {
    51. e.printStackTrace();
    52. }
    53. }
    54. if (!pool.isEmpty()) {
    55. conn = pool.removeFirst();
    56. }
    57. return conn;
    58. } finally {
    59. lock.unlock();
    60. }
    61. }
    62. // Release database connection
    63. public void releaseConnection(Connection conn) {
    64. if (conn != null) {
    65. lock.lock();
    66. try {
    67. // Releasing a connection is the process of putting the connection back into the connection pool
    68. pool.addLast(conn);
    69. condition.signal();
    70. } finally {
    71. lock.unlock();
    72. }
    73. }
    74. }
    75. }

     

Topics: Java Database Big Data