Java 17 Recipes


-2. Connecting to a Database


Download 3.2 Mb.
Pdf ko'rish
bet220/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   216   217   218   219   220   221   222   223   ...   245
Bog'liq
Java 17 Recipes

12-2. Connecting to a Database
 Problem
You want to connect to a database from within a desktop Java application.
 Solution
Use a JDBC Connection object to obtain the connection. Do this by creating a new 
connection object, and then load the driver that you need to use for your particular 
database vendor. Once the connection object is ready, call its getConnection() method. 
The following code demonstrates how to obtain a connection to a MySQL database: in 
general, the connection depends on the specified driver.
package org.java17recipes.chapter12.recipe12_02;
import java.sql.Connection;
import java.sql.DriverManager;
Chapter 12 Working With Databases


432
import java.sql.SQLException;
import java.util.Properties;
public class CreateConnection {
static Properties props = new Properties();
String hostname = "localhost";
String port = "3306";
String database = "apressbooks";
String username = "root";
String password = "root";
public Connection getConnection() throws SQLException {
Connection conn = null;
String jdbcUrl;
jdbcUrl = "jdbc:mysql://" + this.hostname + ":" +
this.port + "/" + this.database;
System.out.println(jdbcUrl);
conn = DriverManager.getConnection(jdbcUrl, this.username, 
this.password);
System.out.println("Successfully connected");
return conn;
}
public static void main(String[] args) {
CreateConnection createConnection = new CreateConnection();
try {
createConnection.getConnection();
} catch (SQLException e){
e.printStackTrace();
}
}
}
The method portrayed in this example returns a Connection object that is ready to 
be used for database access.
Chapter 12 Working With Databases


433

Download 3.2 Mb.

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




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