Connect MySQL Database in Java
Since Java is one of the more popular programming languages, it naturally offers strong support for databases. Using JDBC (Java Database Connectivity), we are able to establish connections to numerous databases. Here, you'll learn how to use JDBC to communicate with a database while running queries.Introduction
JDBC is the default Java API for establishing connections to common relational databases. Here, you'll learn how to utilize Java as well as JDBC to connect to MySQL databases hosted on Azure.In this post, we'll cover two different kinds of authentication: those based on Azure Active Directory (Azure AD) as well as those based on MySQL. To see how Azure Active Directory authentication works, click the Passwordless tab, while the Password tab displays MySQL authentication.
Linking to Azure Database for MySQL with an Azure Active Directory account is possible via the Azure AD authentication mechanism. Using Azure Active Directory (AD) authentication, databases as well as other Microsoft services can have their user identities and permissions managed in one place.
MySQL logs in users with MySQL accounts.
MySQL logs in users with MySQL accounts.
Table of Contents:
- Introduction to JDBC
- Common JDBC Components
- Steps to create JDBC Application
- JDBC Connections
Introduction to JDBC
When it comes to connecting the Java programming language as well as various databases, JDBC makes up one of the mainstream Java APIs. You can use SQL to encode your access request statements with this API. The primary steps here are connection establishment, database creation, SQL query execution, and finally output generation.Every tabular data saved in a relational database is accessible using the JDBC API. You can use this to make changes to, save to, retrieve from, as well as delete information from your database. It's very much like Microsoft's ODBC (Open Database Connectivity) service.
Let's delve deeper into the issue and examine the framework underlying Java Database Connectivity in order to get a better feel for how JDBC operates.
Let's delve deeper into the issue and examine the framework underlying Java Database Connectivity in order to get a better feel for how JDBC operates.
Common JDBC Components
Interfaces as well as classes provided by the JDBC API are as follows:
Moving on to another section, we'll examine the necessary actions for developing a JDBC Application.
DriverManager:
The Operator:
A connection:
Moving on to another section, we'll examine the necessary actions for developing a JDBC Application.
Steps to establish JDBC Application
There are a few measures you must take to make a JDBC Application. What are they, exactly?- Import packages:
In order to use JDBC classes for programming databases, you must import all the relevant libraries. In most cases, import java.sql.* will do the trick.
- Prepare the JDBC driver for use:
- Create a link:
- To conduct a search:
- Data mining the final set of results:
- Clean up environment:
Now that you know what's required to make a JDBC Application, let's look at some sample code to set up a database as well as connect to it.
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RetrieveDataFromDatabase {
public static void main(String[] args) {
// Database connection information
String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";
// SQL query to retrieve data
String sqlQuery = "SELECT id, first_name, last_name, age FROM your_table";
try (
// Establish a database connection
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
// Create a prepared statement with the SQL query
PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
// Execute the query and retrieve the ResultSet
ResultSet resultSet = preparedStatement.executeQuery()) {
// Iterate through the ResultSet and print the data
while (resultSet.next()) {
int id = resultSet.getInt("id");
String firstName = resultSet.getString("firstName");
String lastName = resultSet.getString("lastName");
int age = resultSet.getInt("age");
System.out.println("ID: " + id);
System.out.println("First Name: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Age: " + age);
System.out.println("--------------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This is the way you connect to the database and update the tables with new data. Let's take this a step further by learning about the many kinds of JDBC drivers.
Types of JDBC Driver
Connecting to a database server requires a JDBC driver, which is software that implements the JDBC API's predefined interfaces. There are three primary functions of a JDBC driver.- Connects to a data source in the first place.
- It will communicate with the data source by issuing queries as well as update statements.
- The third and last step is processing the data.
The next step is to learn about JDBC Connections.
JDBC Connections
- JDBC Package Importation:
Include import lines in the Java code to bring in the necessary classes.
- Installing a JDBC Driver:
- Using Java's forName() method to dynamically load the driver's class file into memory and enroll it is the best practice for driver registration. The flexibility and portability of the driver registration system make this approach a good fit. Read the following piece of code:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
- The static registerDriver()method is another option for driver registration.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
If you're using a JVM that isn't JDK compliant, like Microsoft's, you need to call registerDriver(). Each of the forms here necessitates a unique database address.
conn.close(); // Used to close the connection.
- Database URL Formulation:
- getConnection(String url)
- getConnection(String url, Properties prop)
- getConnection(String url, String user, String password)
- Build a connection object
- Close
conn.close(); // Used to close the connection.
Comments
Post a Comment