Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
How It Works
Creating a JDBC connection involves a few steps. First, you need to determine which database driver you need. After you’ve determined which driver you need, you download the JAR file containing that driver and place it into your classpath. Each database vendor provides different JDBC drivers packaged in JAR files with different names; consult the documentation for your database for more information. For this recipe, you can download the connector at https://dev.mysql.com/downloads/connector/j/ . Ensure that the selected platform is “Platform Independent”: this is important for distributing the software on different systems. Next, use a JDBC DriverManager class to obtain a connection to the database. To obtain a connection to your database using the DriverManager class, you need to pass a string containing the JDBC URL to it. The JDBC URL consists of the database vendor name, along with the name of the server that hosts the database, the name of the database, the database port number, and a valid database username and password that has access to the schema or database objects that you want to work with. The values to create the JDBC URL are often obtained from a Properties file so that they can be easily changed if needed. The code that creates the MySQL database JDBC URL for solution 1 looks like the following. String jdbcUrl = "jdbc:mysql:thin:@" + this.hostname + ":" + this.port + ":" + this.database; Once all the variables have been substituted into the string, it looks like the following. jdbc:mysql://localhost:3306/apressbooks Once the JDBC URL has been created, it can be passed to the DriverManager .getConnection() method to obtain a java.sql.Connection object. If incorrect information has been passed to the getConnection() method, java.sql.SQLException is thrown; otherwise, a valid Connection object is returned. Chapter 12 Working With Databases |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling