The Update Statement in SQL updates the existing records in a table. In JDBC the Prepared Statement Update is used to update the SQL statement, using where clause, that specify which records is updated.
Understand with Example
The Tutorial illustrates a code that help you in understanding JDBC Prepared Statement Update. The code include a class Jdbc Prepared Statement, this class include a main method ( ), Inside the main method we have a list of steps -
Importing a package java.sql - This package provides you a network interface, that enables you to communicate between front end application -back end. Loading a driver by calling a class.forName ( ),that accept a driver class as argument.
DriverManager.get Connection ( ) -The Driver Manager call a getConnection ( ) method, return you a connection object, built a connection between url and database.
The connection object call a prepareStatement ( ),that is used to update the table stu using where clause, specify the name of record to be updated at runtime. The set String XXX return you a set value in the place of question mark holder. The executeQuery ( ) return you the record set from a updated table in the database.
Finally the println print the updated table from the database in output. The catch block caught the exception in try block.
JdbcPreparedstatementUpdate.java
import java.sql.*;
public class JdbcPreparedstatementUpdate {
public static void main(String args[]) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
pst = con.prepareStatement("update stu set class=? where id =?");
pst.setString(1, "11");
pst.setString(2, "1");
pst.executeUpdate();
pst = con.prepareStatement("select * from stu");
rs = pst.executeQuery();
System.out.println("Id\tName\tClass");
while (rs.next()) {
System.out.print(rs.getString(1) + "\t");
System.out.print(rs.getString(2) + "\t ");
System.out.println(rs.getString(3));
}
rs.close();
pst.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
Id Name Class 1 komal 11 2 santosh 11 3 rakesh 9 4 ajay 11 5 bhanu 10 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: JDBC Prepared Statement Update View All Comments
Post your Comment