官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 德格县| 文登市| 乃东县| 溧阳市| 郸城县| 扶绥县| 凤阳县| 太谷县| 阜新| 南郑县| 吴旗县| 临漳县| 临朐县| 招远市| 拉萨市| 呼玛县| 牡丹江市| 旌德县| 斗六市| 曲周县| 辰溪县| 高碑店市| 伊通| 阿克| 义马市| 玛多县| 乐业县| 无锡市| 临武县| 双江| 临桂县| 沂水县| 体育| 江永县| 齐河县| 隆子县| 亳州市| 鄂托克前旗| 盘锦市| 杨浦区| 西畴县|