How to Update Contents of a Table using JDBC Connection?
JDBC (Java Database Connectivity) is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend( for storing data).
Steps to Update the contents of a table using JDBC
1. Create Database: You can create a database using SQLyog and create some tables in it and fill data inside it in order to update the contents of a table. Here, for example, the name of my database is hotelman, and table names are cuslogin and adminlogin. We will be taking cuslogin table as an example.
2. Create Connection: Open Netbeans and create a new package. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.
3. Update Contents In a Table: Let’s suppose we want to update the customer name from cuslogin table whose id is 2.
Initialize a string with the SQL query as follows
String sql="update cuslogin set name='GFG' where id=2";
Initialize the below objects of Connection class, PreparedStatement class(needed for jdbc), and connect with the database as follows
Connection con=null; PreparedStatement p=null; con=connection.connectDB();
Now, add the SQL query given above, inside prepareStatement and execute it as follows
p =con.prepareStatement(sql); p.execute();
Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for updating the name of the customer whose id is 2, from table cuslogin.
Note: both the file’s viz result.java and connection.java should be inside the same package, else the program won’t give the desired output!!
After running the result.java, the output can be seen in SQLyog as follows:
We can see, the customer whose id is 2, now has the name GFG.