To connect to a MySQL database using JDBC, you will need to follow these steps:
- Load the MySQL JDBC driver class:
Class.forName("com.mysql.cj.jdbc.Driver");
- Define the database URL, username and password:
String url = "jdbc:mysql://localhost:3306/mydb"; String username = "user"; String password = "password";
- Create a connection to the database using the DriverManager class:
Connection conn = DriverManager.getConnection(url, username, password);
- Once you have a connection, you can create a Statement object to execute SQL queries:
Statement stmt = conn.createStatement();
- Use the Statement object to execute queries:
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
Following is an example of how all of these steps can be put together:
import java.sql.*; public class MySQLJDBCDemo { public static void main(String[] args) throws SQLException, ClassNotFoundException { // Load the MySQL JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Define the database URL, username and password String url = "jdbc:mysql://localhost:3306/mydb"; String username = "user"; String password = "password"; // Create a connection to the database Connection conn = DriverManager.getConnection(url, username, password); // Create a Statement object to execute queries Statement stmt = conn.createStatement(); // Execute a query and get the result set ResultSet rs = stmt.executeQuery("SELECT * FROM mytable"); // Loop through the result set and print the data while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } // Close the result set, statement and connection rs.close(); stmt.close(); conn.close(); } }
Note that you will need to replace the database URL, username and password in the above example with the appropriate values for your MySQL database.