Creating database connections

Make sure that the JDBC driver for the database you want to connect to is downloaded and is in the classpath. In our project, we have already ensured this by adding a dependency in Maven. Maven downloads the driver and adds it to the class path of our web application.

It is always a good practice to make sure that the JDBC driver class is available when the application is running. If it is not, we can set a suitable error message and not perform any JDBC operations. The name of the MySQL JDBC driver class is com.mysql.cj.jdbc.Driver:

try { 
  Class.forName("com.mysql.cj.jdbc.Driver"); 
} 
catch (ClassNotFoundException e) { 
  //log excetion 
  //either throw application specific exception or return 
  return; 
} 
 

Then, get the connection by calling the DriverManager.getConnection method:

try { 
  Connection con = 
DriverManager.getConnection("jdbc:mysql://localhost:3306/schema_name?" + "user=your_user_name&password=your_password"); //perform DB operations and then close the connection con.close(); } catch (SQLException e) { //handle exception }

The argument to DriverManager.getConnection is called a connection URL. It is specific to the JDBC driver. So, check the documentation of the JDBC driver to understand how to create a connection URL. The URL format in the preceding code snippet is for MySQL. See https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-configuration-properties.html.

The connection URL contains the following details: hostname of the MySQL database server, port on which it is running (default is 3306), and the schema name (database name that you want to connect to). You can pass username and password to connect to the database as URL parameters.

Creating a connection is an expensive operation. Also, database servers allow a certain maximum number of connections to it, so connections should be created sparingly. It is advisable to cache database connections and reuse. However, make sure that you close the connection when you no longer need it, for example, in the final blocks of your code. Later, we will see how to create a pool of connections so that we create a limited number of connections, take them out of the pool when required, perform the required operations, and return them to the pool so that they can be reused.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.113.163