Update record using preparedStatement:
- We read the input from the user to update the data.
- PrepareStatement object is used for data updation.
- executeUpdate() method must be called for this updation.
package online;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Scanner;
public class RecordUpdate
{
static Connection con;
public static void main(String args[]) throws Exception
{
Scanner scan = new Scanner(System.in);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Driver is ready");
con = DriverManager.getConnection(" jdbc:oracle:thin:@localhost:1521:xe", "system", "admin");
System.out.println("Connection is ready");
System.out.print("Enter account number : ");
int acc = scan.nextInt();
System.out.print("Enter deposit amount : ");
int amt = scan.nextInt();
String query = "update account set balance=balance+? where num=?";
PreparedStatement stmt=con.prepareStatement(query);
stmt.setInt(1, amt);
stmt.setInt(2, acc);
int count = stmt.executeUpdate();
System.out.println("Updated record(s) : " + count);
}
finally
{
if(con != null)
{
con.close();
System.out.println("Connection closed");
}
}
}
}
package online; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.Scanner; public class RecordUpdate { static Connection con; public static void main(String args[]) throws Exception { Scanner scan = new Scanner(System.in); try { Class.forName(“oracle.jdbc.driver.OracleDriver”); System.out.println(“Driver is ready”); con = DriverManager.getConnection(” jdbc:oracle:thin:@localhost:1521:xe”, “system”, “admin”); System.out.println(“Connection is ready”); System.out.print(“Enter account number : “); int acc = scan.nextInt(); System.out.print(“Enter deposit amount : “); int amt = scan.nextInt(); String query = “update account set balance=balance+? where num=?”; PreparedStatement stmt=con.prepareStatement(query); stmt.setInt(1, amt); stmt.setInt(2, acc); int count = stmt.executeUpdate(); System.out.println(“Updated record(s) : ” + count); } finally { if(con != null) { con.close(); System.out.println(“Connection closed”); } } } } |