JDBC Statement
Introduction to JDBC Statement
Java Database Connectivity (JDBC) Statement is a fundamental concept in Java that allows us to interact with databases and perform CRUD (Create, Retrieve, Update, Delete) operations. The java.sql.Statement
interface provides methods to execute queries with the database. The statement object is used to send SQL commands to the database and retrieve the results.
Establishing the Connection
Before we can create a Statement, we first need to establish a connection with our database. Here's a simple example of how you can do this:
import java.sql.*;
public class JdbcConnection {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb","root","password");
} catch (Exception e) {
e.printStackTrace();
}
}
}
This will load the driver class, and establish a connection to the MySQL database mydb
.
Creating a Statement
Once the connection is established, we can create a Statement object using the createStatement()
method of the Connection object:
Statement stmt = con.createStatement();
Executing Queries
The Statement
interface provides three methods for executing queries:
executeQuery(String sql)
: This is used to execute SELECT queries. It returns aResultSet
object which contains the result returned by the query.executeUpdate(String sql)
: This is used to execute INSERT, DELETE, and UPDATE queries. It returns an integer representing the number of rows affected by the query.execute(String sql)
: This is used to execute any kind of SQL query. It returns a boolean value indicating whether the result is aResultSet
object or an integer.
Here's an example of how to execute a SELECT query:
ResultSet rs = stmt.executeQuery("SELECT * FROM Students");
while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
And here's an example of how to execute an INSERT query:
int result = stmt.executeUpdate("INSERT INTO Students VALUES (1, 'John')");
System.out.println(result + " records inserted.");
Closing the Statement and Connection
After we're done with our database operations, it's important to close the Statement and Connection objects to free up database resources. This can be done using the close()
methods:
stmt.close();
con.close();
Conclusion
That's a basic introduction to JDBC Statement in Java. Remember, when using Statement, every SQL command is treated as a separate string and passed to the database directly, making it vulnerable to SQL Injection attacks. In such cases, it's recommended to use PreparedStatement, which we will cover in a separate guide. Happy coding!