Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet221/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   217   218   219   220   221   222   223   224   ...   245
Bog'liq
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


434

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   217   218   219   220   221   222   223   224   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling