- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to update(delete, insert or update) contents of a table using JDBC connection in Java
Problem Description
How to update(delete, insert or update) contents of a table using JDBC connection?
Solution
Following method uses update, delete & insert SQL commands to edit or delete row contents.
import java.sql.*; public class updateTable { public static void main(String[] args) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); } catch(ClassNotFoundException e) { System.out.println("Class not found "+ e); } try { Connection con = DriverManager.getConnection ( "jdbc:derby://localhost:1527/testDb","username", "password"); Statement stmt = con.createStatement(); String query1 = "update emp set name = 'ravi' where id = 2"; String query2 = "delete from emp where id = 1"; String query3 = "insert into emp values (1,'ronak','manager')"; stmt.execute(query1); stmt.execute(query2); stmt.execute(query3); ResultSet rs = stmt.executeQuery("SELECT * FROM emp"); System.out.println("id name job"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String job = rs.getString("job"); System.out.println(id+" "+name+" "+job); } } catch(SQLException e) { System.out.println("SQL exception occured" + e); } } }
Result
The above code sample will produce the following result. The result may vary.
id name job 2 ravi trainee 1 ronak manager
java_jdbc.htm
Advertisements
To Continue Learning Please Login
Login with Google