Java Database Connectivity (JDBC) is an API that allows Java applications to connect and interact with databases. Using JDBC, Java programs can connect to MySQL, execute SQL queries, and process results efficiently.
Click the button below to visualize how Java connects to the Database.
To connect Java with MySQL, the JDBC driver must be loaded, a connection URL must be provided, and valid database credentials are required.
// Import JDBC classes
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class MySQLConnectionDemo {
public static void main(String[] args) {
try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create connection to MySQL database
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);
// Create statement object
Statement stmt = con.createStatement();
// Connection successful message
System.out.println("Connected to MySQL database successfully");
con.close();
} catch (Exception e) {
// Handle any errors
e.printStackTrace();
}
}
}
When the program runs successfully, it prints:
Connected to MySQL database successfully
This confirms that Java has successfully established a connection with the MySQL database.