How to Create a Connection to MySQL
A Connection is a link between two systems that allows them to exchange information. In Java, a Connection is an object from the java.sql.Connection interface that represents a session between a Java application and a database.
A Connection in Java is established through JDBC, allowing a Java application to send SQL statements to the database and receive results.
Required Steps:
• Import the packages: You need to include the packages that contain the JDBC classes required for database programming. In most cases, importing java.sql.* is sufficient.
• Open a connection: Use the DriverManager.getConnection() method to create a connection object that represents a physical connection to the database server.
• To create a new database: You do not need to specify any database name while preparing the database URL, as shown in the example below.
• Execute a query: You need to use an object of type Statement to create and send SQL statements to the database.
Example 1: Creating a Connection in Java
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connection details
String url = "jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=Asia/Phnom_Penh";
String user = "root"; // MySQL username
String password = "root"; // MySQL password
// Connect
conn = DriverManager.getConnection(url, user, password);
// Success message
JOptionPane.showMessageDialog(this, "Connected to Database Successfully!");
} catch (Exception e) {
// Error message
JOptionPane.showMessageDialog(this, "Connection Failed: " + e.getMessage());
} finally {
try { if (conn != null) conn.close(); } catch (Exception ex) {}
}
}
Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

