JDBC (Java Database Connectivity) is a Java API that allows Java applications to interact with databases.
Following are the 6 steps to execute JDBC query:
- Register the JDBC driver
- Open a database connection
- Create a statement
- Execute the query
- Process the result
- Close the resources
Register the JDBC driver
Before we can interact with a database using JDBC, we need to register the JDBC driver. This is typically done using the Class.forName()
method, which loads the driver class into memory.
Open a database connection
After the driver is registered, we can use the DriverManager.getConnection()
method to establish a connection to the database. This method returns a Connection
object that represents the connection to the database.
Create a statement
Once we have a connection to the database, we can create a Statement
object using the Connection.createStatement()
method. This object represents a SQL statement that we want to execute.
Execute the query
To execute the query, we call one of the Statement.execute*()
methods (e.g. executeQuery()
, executeUpdate()
, etc.) with the SQL statement we want to execute. The method returns a ResultSet
object if the query returns data, or an integer representing the number of rows affected if the query is an update, insert or delete.
Process the result
If the query returned data, we can use the ResultSet
object to iterate over the rows of data. The ResultSet
provides methods to get the values of the columns for each row.
Close the resources
After we finished using the ResultSet
, we must close it using the ResultSet.close()
method. We can also close the Statement
and Connection
objects using their close()
methods.
Example
The complete example code is given below:
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// Register the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
// Create a statement
Statement stmt = conn.createStatement();
// Execute the query
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// Process the result
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}
// Close the resources
rs.close();
stmt.close();
conn.close();
}
}