0% found this document useful (0 votes)
41 views1 page

PreparedStatement JDBC

The document explains the PreparedStatement interface in JDBC, which is used for executing parameterized queries. It provides an example of inserting data into a database using PreparedStatement and demonstrates how to set parameters and execute the query. The code snippet shows the process of connecting to a MySQL database, inserting a record, and retrieving data from the 'Persons' table.

Uploaded by

detata2288
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views1 page

PreparedStatement JDBC

The document explains the PreparedStatement interface in JDBC, which is used for executing parameterized queries. It provides an example of inserting data into a database using PreparedStatement and demonstrates how to set parameters and execute the query. The code snippet shows the process of connecting to a MySQL database, inserting a record, and retrieving data from the 'Persons' table.

Uploaded by

detata2288
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Prepared Statement in JDBC

• The PreparedStatement interface is a sub interface of Statement.


• It is used to execute parameterized query.
• For example: String sql="insert into emp values(?,?,?)";
• Here, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of
PreparedStatement like setInt(int paramIndex, int value), etc.

import java.sql.*;
class JDBCPrepared
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.cj.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Test
?useSSL=false","root","123456");

PreparedStatement stmt=con.prepareStatement("insert into Persons


values(?,?,?)");
stmt.setInt(1,112);//1 specifies the first parameter in the query
stmt.setString(2,"Rohan");
stmt.setString(3,"6666666666");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
ResultSet rs=stmt.executeQuery("select * from Persons");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}

con.close();

}
catch(Exception e)
{
System.out.println(e);
}
}
}

You might also like