JDBC
Statements
Types of Statements in JDBC
JDBC provides three types of statements for executing SQL
commands:
- Statement
- PreparedStatement
- CallableStatement
1.
Statement
Statement is used to execute simple and static SQL
statements that do not require input parameters. The SQL query is written
directly as a string and sent to the database for execution. It is commonly
used for basic SELECT, INSERT, UPDATE, and DELETE operations.
Example:
Statement
stat = conc.createStatement();
Stat.executeUpdate(“INSERT
into Department values(205, ‘IT’)”);
ResultSet
rs = stat.executeQuery("SELECT * FROM Department where deptCode=205");
2.
PreparedStatement
PreparedStatement is used to execute parameterized
SQL statements. It uses ? as placeholders for values, which are supplied
using methods such as setInt() and setString(). It is useful when the same SQL
statement needs to be executed with different values.
Example:
PreparedStatement ps = conc.prepareStatement("SELECT
* FROM Department WHERE DeptCode = ?");
ps.setInt(1,
205);
ResultSet
rs = ps.executeQuery();
3.
CallableStatement
CallableStatement is used to execute stored
procedures in a database. A stored procedure is a set of SQL statements
stored and executed on the database server. It can accept input parameters and
can also return output parameters.
Step 1: Create a stored procedure in MySQL
Step 2: Call the procedure from Java
Procedure:
DELIMITER //
CREATE PROCEDURE getDepartment(IN val INT)
BEGIN
SELECT *
FROM Department
WHERE DeptCode = val;
END //
DELIMITER ;
CallableStatement
cs = conc.prepareCall("{call getDepartment(205)}");
ResultSet
rs = cs.executeQuery();
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu