JDBC (Java Database Connectivity) is a Java API that allows Java programs to interact with databases. JDBC statements are used to execute SQL queries or updates against a database.
Following is an example of how to work with JDBC statements in Java:
- First, we need to establish a connection to the database using the JDBC driver. Following is an example of how to connect to a MySQL database:
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) throws SQLException {
// Connect to MySQL database
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
}
}
- Once we have established a connection, we can create a statement object. The statement object is used to execute SQL queries or updates against the database.
Statement stmt = conn.createStatement();
- We can then execute SQL queries or updates using the statement object. Following is an example of how to execute a simple select statement:
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable"); while (rs.next()) { // Access result set data int id = rs.getInt("id"); String name = rs.getString("name"); // Do something with data }
- Finally, it is best practice to close the statement and connection objects when we are done with them to remove unwanted resource uses:
stmt.close(); conn.close();
That’s a basic overview of how to work with JDBC statements in Java. There are many other things we can do with JDBC, such as executing prepared statements, calling stored procedures, and managing transactions.