PreparaedStatement in JDBC?
It is used to manage SQL Statement Data using a parametrized pattern.it is a subinterface of Statement Interface.
Code for Insert using Prepared Statement:-
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schooldb","root","");
//PreparedStatement st = conn.prepareStatement("insert into student values(?,?,?,?)");
st.setInt(1,1111);
st.setString(2,"xyz");
st.setString(3,"CS");
st.setInt(4,55000);
int x = st.executeUpdate();
if(x!=0){
System.out.println("Data Inserted Successfully");
}
else
{
System.out.println("Data NOT Inserted Successfully");
}
}
catch(Exception ex)
{ System.out.println(ex.getMessage());
}
Code for Update:-
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schooldb","root","");
//PreparedStatement st = conn.prepareStatement("insert into student values(?,?,?,?)");
PreparedStatement st = conn.prepareStatement("update student set sname=?,branch=?, fees=? where rno=?)");
st.setString(1,"xyz");
st.setString(2,"CS");
st.setInt(3,55000);
st.setInt(4,1111);
int x = st.executeUpdate();
if(x!=0){
System.out.println("Data Updated Successfully");
}
else
{
System.out.println("Data NOT Updated Successfully");
}
Code for Delete
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schooldb","root","");
//PreparedStatement st = conn.prepareStatement("insert into student values(?,?,?,?)");
//PreparedStatement st = conn.prepareStatement("update student set sname=?,branch=?, fees=? where rno=?)");
PreparedStatement st = conn.prepareStatement("delete from student where rno=?)");
st.setInt(1,1111);
int x = st.executeUpdate();
if(x!=0){
System.out.println("Data Deleted Successfully");
}
else
{
System.out.println("Data NOT Deleted Successfully");
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
Code for Select Database?
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schooldb","root","");
//PreparedStatement st = conn.prepareStatement("insert into student values(?,?,?,?)");
//PreparedStatement st = conn.prepareStatement("update student set sname=?,branch=?, fees=? where rno=?)");
PreparedStatement st = conn.prepareStatement("select * from student where rno=?)");
ResultSet x = st.executeQuery();
while(x.next()){
System.out.println(x.getString(1) + " "+ x.getString(2));
}
}
catch(Exception ex)
{ System.out.println(ex.getMessage());
}
POST Answer of Questions and ASK to Doubt