Step 1. Download and Install the MySQL JDBC Driver: First, you need to download the MySQL JDBC driver (usually a JAR file). You can obtain it from the official MySQL website or include it as a dependency if you are using a build tool like Maven or Gradle.
Step 2. Import JDBC Packages: Import the necessary JDBC packages into your Java application.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
Step 3. Establish a Database Connection: Create a connection to your MySQL database by specifying the database URL, username, and password.
String url = "jdbc:mysql://localhost:3306/yourdatabase";
String user = "username";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
Step 4. Create a Statement or PreparedStatement: You can use Statement
for static SQL queries or PreparedStatement
for parameterized queries.
// Statement example
Statement statement = connection.createStatement();
// PreparedStatement example
String sqlQuery = "INSERT INTO yourtable (column1, column2) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
Step 5. Execute SQL Queries: Execute the SQL queries based on your requirements.
// Execute SELECT query
String selectQuery = "SELECT * FROM yourtable";
ResultSet resultSet = statement.executeQuery(selectQuery);
// Execute INSERT, UPDATE, or DELETE query using PreparedStatement
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
int rowsAffected = preparedStatement.executeUpdate();
Step 6. Process the Results: If you executed a SELECT query, iterate through the result set to retrieve data.
while (resultSet.next()) {
// Process each row of data
}
Step 7. Close Resources: Always close the database resources when you’re done with them.
resultSet.close();
statement.close();
preparedStatement.close();
connection.close();