PreparedStatement in Java - Javastudypoint

Wednesday, September 5, 2018

PreparedStatement in Java


PreparedStatement is an interface, which is available in java.MySQL package
It extends the Statement interface.

Why we use PreparedStatement?

  • It can be used to execute dynamic and parametrized SQL Query.
  • Prepared Statement is faster then Statement interface. Because in Statement Query will be compiled and execute every time, while in case of Prepared Statement Query won't be compiled every time just executed.
  •  It can be used for both static and dynamic query.
  • In case of Prepared Statement no chance of SQL Injection attack. It is some kind of problem in database programming.
Suppose, I have an SQL Query. In this SQL Query, we have to use username and password. This query is checking username and password is valid or not. Because the end user provided input the query behavior is changing, it is not checking username and password is valid or not. If you change the behavior of the SQL query by adding special character in end user provided input this problem is known as SQL Injection attack.


PreparedStatement Methods in java:

The important methods of PreparedStatement are given below:

1) public void setInt( int parameter index, int value): This method is used to set the integer value to the given parameter index.

2) public void setString(int parameter index, int value): This method is used to set the String value to the given parameter index.

3) public void setFloat(int parameter index, int value): This method is used to set the float value to the given parameter index.

4) public void setDouble(int parameter index, int value): This method is used to set the double type value to the given parameter index.

5) public int executeUpdate(String url): If you want to modify in your database you should go for executeUpdate() method. This method returns an integer value which indicates the number of rows affected.

6) public ResultSet executeQuery(String url): This method is used for the select statement which retrieves some data from the database. This method returns a ResultSet.

Example of Prepared Statement in java :

preparedStatement in java

output:

preparedStatement in java

                        


preparedStatement in java



You may also like:





1 comment: