Executing SQL Queries
In JDBC, you can execute SQL queries using different types of statements, such as Statement, PreparedStatement, and CallableStatement. Each type of statement has its own use case and advantages. Here, I'll provide examples of how to execute SQL queries using each of these statement types.
Before running these examples, ensure that you have a MySQL database set up, and you have the MySQL JDBC driver in your classpath.
1. Using Statement to Execute SQL Queries
Statement to Execute SQL Queriesimport java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class StatementExample {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "your_username", "your_password");
Statement statement = connection.createStatement();
// Execute a SELECT query
ResultSet resultSet = statement.executeQuery("SELECT * FROM your_table_name");
// Process the results
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// Close the resources
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}2. Using PreparedStatement to Execute SQL Queries
PreparedStatement to Execute SQL Queries3. Using CallableStatement to Execute SQL Queries
CallableStatement to Execute SQL QueriesCallable statements are typically used for calling stored procedures in databases. Here's a basic example:
Make sure to replace "your_database", "your_username", "your_table_name", "your_stored_procedure", and any placeholders with your actual database information and SQL statements. Handle exceptions properly in a real application for robust error handling.
Last updated
Was this helpful?