java tutorial - Prepared statement java - java programming - learn java - java basics - java for beginners
PreparedStatement interface
- The PreparedStatement interface is the sub interface of the Statement.
- It is used to execute parameterized query.
Parameterized query
- You can see, you are passing parameter (?) for the values.
- Its value can be a set by calling the setter methods of PreparedStatement.
Why we use PreparedStatement in java ?
- Improves performance: The PreparedStatement is faster in application, if we use PreparedStatement interface, the query is compiled only one time.
How to get the instance of PreparedStatement ?
- The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.
Syntax
Methods of PreparedStatement interface
Method | Description |
---|---|
public void setInt(int paramIndex, int value) | sets the integer value to the given parameter index. |
public void setString(int paramIndex, String value) | sets the String value to the given parameter index. |
public void setFloat(int paramIndex, float value) | sets the float value to the given parameter index. |
public void setDouble(int paramIndex, double value) | sets the double value to the given parameter index. |
public int executeUpdate() | executes the query. It is used to create, drop, insert, update, delete and so on. |
public ResultSet executeQuery() | executes the select query. It returns an instance of ResultSet. |
Sample Code
- In this example we will execute a SQL statement using PreparedStatement object.
- In this example we will use "INSERT INTO" SQL statement.
- An INSERT INTO statement is used to insert the value into the database table.
- In this example we will first create a database table using MySQL and then we will create a Java classes into which we will use the classes and interfaces of java.sql package for making connection with database and to insert value into the database table.