Introduction

In this blog we will know how to update records from database using JDBC (Java Database Connectivity) in the console window.
Here we use Type-1 driver (JDBC-ODBC bridge)

Creation of dsn(database source name) for Oracle

Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system DSN tab-click add button-select a driver for which you want to set up a data source (for Oracle- Oracle in XE)-select it and click finish-give any name in the data source name textbox-then click ok button.
Note: - Here Username=system, Password=pintu and Dsn name=dsn1

Table Creation

Create table employee (empno int,empname varchar(50),sal int)
Example:- To update record in a table
  1. import java.sql.*;
  2. import java.util.*;
  3. public class update
  4. {
  5. public static void main(String args[]) throws Exception
  6. {
  7. Scanner sc = new Scanner(System.in);
  8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  9. Connection con = DriverManager.getConnection("jdbc:odbc:dsn1", "system", "pintu");
  10. Statement stmt = con.createStatement();
  11. System.out.print("Enter the Employee number: ");
  12. int x = sc.nextInt();
  13. System.out.print("Enter the new salary : ");
  14. int z = sc.nextInt();
  15. System.out.print("Enter the Employee name: ");
  16. String y = sc.next();
  17. String sql = "update employee set sal=" + z + ",empname='" + y + "' where empno=" + x;
  18. int no = stmt.executeUpdate(sql);
  19. if (no > 0)
  20. System.out.println(no + " Records Successfully Updated");
  21. else
  22. System.out.println("Invalid employee number");
  23. con.close();
  24. }
  25. }
Compile
Javac update.java
Java update