The Wayback Machine - https://web.archive.org/web/20240921071832/https://www.geeksforgeeks.org/how-to-update-contents-of-a-table-using-jdbc-connection/
Open In App

How to Update Contents of a Table using JDBC Connection?

Last Updated : 08 Dec, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Create a DatabaseTable Data

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.

Java




// Java program to create a connection to a database
  
import java.sql.*;
  
public class connection {
  
    // Connection instance
    Connection con = null;
  
    public static Connection connectDB()
    {
        try {
            Class.forName("com.mysql.jdbc.Driver");
  
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/hotelman",
                "root", "1234");
            
            // here,root is the username and 1234 is the
            // password,you can set your own username and
            // password.
            return con;
        }
        catch (SQLException e) {
  
            System.out.println(e);
        }
    }
}


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!!

Java




// Java Program to Update contents in a table
  
import java.sql.*;
public class result {
  
    public static void main(String[] args)
    {
        Connection con = null;
        PreparedStatement p = null;
        con = connection.connectDB();
        try {
            String sql
                = "update cuslogin set name='GFG' where id=2";
            p = con.prepareStatement(sql);
            p.execute();
        }
        catch (SQLException e) {
            System.out.println(e);
        }
    }
}


After running the result.java, the output can be seen in SQLyog as follows:

Updated table

We can see, the customer whose id is 2, now has the name GFG.



Similar Reads

Java Program to Retrieve Contents of a Table Using JDBC connection
It can be of two types namely structural and non-structural database. The structural database is the one which can be stored in row and columns. A nonstructural database can not be stored in form of rows and columns for which new concepts are introduced which would not be discussing here. Most of the real-world data is non-structural like photos, v
5 min read
Delete Contents From Table Using JDBC
JDBC(Java Database Connectivity) is 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). Approach: 1. CREATE DATABASE: Create a database using sqlyog and create some tables in
2 min read
Java Program to Search the Contents of a Table in JDBC
In order to deal with JDBC standard 7 steps are supposed to be followed: Import the databaseLoad and register driversCreate a connectionCreate a statementExecute the queryProcess the resultsClose the connectionProcedure: Import the database-syntax for importing the sql database in java is- import java.sql.* ;Load and register drivers-syntax for reg
5 min read
Java Program to Join Contents of More than One Table & Display in JDBC
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. First, need to decide, which database we are using and accordingly, we need to add the jars. For other databases like Progress, Cassandra, etc also we have jars and need to include them in t
5 min read
How to Sort Contents of a Table in JDBC?
Sorting the contents of a table means rearranging the records in an organized way to make data more usable. You can sort all the records of a table by choosing a column within a table according to which data has to be sorted. In simple words, when you sort data, you arrange the data in a logical order. Text and Numbers both can be sorted in any ord
4 min read
How to Insert Records to a Table using JDBC Connection?
Before inserting contents in a table we need to connect our java application to our database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications-to-JDBC connection and JDBC driver provid
4 min read
Java JDBC - Update a Column in a Table
Java has its own API which JDBC API which uses JDBC drivers for database connections. JDBC API provides the applications-to-JDBC connection and JDBC driver provides a manager-to-driver connection. Following are the 5 important steps to connect java application to our database using JDBC. Registering the Java classCreating a ConnectionCreating a Sta
2 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Establishing JDBC Connection in Java
Before Establishing JDBC Connection in Java (the front end i.e your Java Program and the back end i.e the database) we should learn what precisely a JDBC is and why it came into existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to get it working. What is JDBC? JDBC is an acronym for
6 min read
How to Implement Connection Timeout with HikariCP in JDBC?
HikariCP is a lightweight, high-performance JDBC connection pooling library that provides fast and efficient management of database connections for Java applications. In this article, we are going to implement a connection timeout with HikariCP. HikariCP LibraryLet's ensure that we have the HikariCP library added to our Java project's dependencies.
3 min read
How to handle connection leaks in JDBC?
In this article, we will learn how to handle connection leaks in JDBC. Handling connection leaks in JDBC involves ensuring that database connections are properly closed after they are no longer needed. The connection leaks occur when a connection is opened but not closed. Due to connection leaks, there is a chance of loss of data, so we need to clo
4 min read
How to Handle Connection Pooling in JDBC in Java?
In Java applications, interacting with the databases using JDBC (Java Database Connectivity), and managing the database connections efficiently is crucial for optimal performance and resource utilization. Connection pooling is the technique employed to achieve the goal by reusing the established database connections instead of creating new ones for
5 min read
How to Check Internet Connection in Android with No Internet Connection Dialog?
Hello geeks, today we are going to learn that how we can add the functionality of Internet Alert to our application. You have definitely seen in almost all applications that when data is turned off or application is not able to get Internet then it pops up a message of "No Internet Connection" and then again it is connected to data is displays mess
4 min read
Java Program to Delete a Column in a Table Using JDBC
Before deleting a column in a table, first is need to connect the java application to the database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications to JDBC connection and JDBC driver
3 min read
How to Add a New Column to a Table Using JDBC API?
Java has its own API which JDBC API which uses JDBC drivers for database connections. JDBC API provides the applications-to-JDBC connection and JDBC driver provides a manager-to-driver connection. Following are the 5 important steps to connect the java application to our database using JDBC. Registering the Java classCreating a connectionCreating a
2 min read
How to Get the Datatype of a Column of a Table using JDBC?
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. MySQL: mysql-connector-java-8.0.22 or similar mysql connectors with different versions. In this article, we are using mysql-connector-java-8.0.22SQL Server: sqljdbc4.jarOracle: ojdbc14.jarMo
5 min read
Java Program to Insert Details in a Table using JDBC
Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgres, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data). Algorithm: Search/ Insert/ Delete/ Update in JDBC In order to deal with JDBC s
4 min read
How to Use Different Row Methods to Get Number of Rows in a Table in JDBC?
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. For different databases, different jar files are imported to make a connection given below or their built path is supposed to be added for specific databases. Types of DatabaseSQLMySQL: mysq
5 min read
How to Apply Fonts to the Contents of a Cell Using Java?
In this article, we will learn how to apply the custom font and various styles associated with it using Java and Apache POI (a Java API which is very useful to handle the Microsoft Documents). Approach: Writing a file using POI is very simple and involve following steps: Create a workbook.Create a spreadsheet in workbook.Create a font and apply sty
2 min read
Shrinking the Contents in a PDF using Java
Program to shrink the contents of a PDF document. The external jar file is required to import in the program. Below is the implementation for the same. Approach: 1. Create an empty PDF file. Assign the path of the empty PDF to a String variable.Import PdfWriter from the package com.itextpdf.kernel.pdf. (PdfWriter allows us to write content on our P
5 min read
How to Add Hyperlink to the Contents of a Cell using Java?
Add a hyperlink to a content of the cell using Java and Apache POI. Apache POI is a Java library that is used to handle Microsoft Office Documents. Installation: There are two ways to install the Apache POI dependency in our java project: Download below mentioned Jar files from poi.apache.org/download.html:poi-3.17.jarpoi-ooxml-3.17.jarcommons-code
2 min read
How to add Image to MySql database using Servlet and JDBC
Structured Query Language or SQL is a standard Database language which is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will understand how to add an image to the MYSQL database using servlet. MYSQL is a relational database. Relational database means the da
6 min read
Inserting Records in Batch Using JDBC
It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually built by the database vendor and found on the datab
2 min read
Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
We will be running the SQL scripts with Spring JDBC +JPA + HSQLDB. These scripts are used to perform SQL commands at the time of application start. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. JPA is just a specification that faci
3 min read
How to Call Stored Functions and Stored Procedures using JDBC?
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java applications to communicate with various databases. It provides the language with java database connectivity standards. It is used to write pr
5 min read
Working with Large Objects Using JDBC in Java
Sometimes as part of programming requirements, we have to insert and retrieve large files like images, video files, audio files, resumes, etc with respect to the database. Example: Uploading images on the matrimonial websiteUpload resume on job-related websites To store and retrieve large information we should go for Large Objects(LOBs). There are
5 min read
JDBC Using Model Object and Singleton Class
This article explains how to perform JDBC operation using a Model object and a Singleton connection class from a MySQL database . JDBC is an Application Programming Interface for Java which connects a Java application with a database to perform CRUD operations. Pre requisite: JDK 7+ (Click here to download)MySQL Database (Click here to download)MyS
6 min read
How to Handle SQL Injection in JDBC using PreparedStatement?
In this article, we can learn how to prevent SQL injection in JDBC by using Java programming. Basically, SQL injection is a type of security vulnerability It occurs when hackers or attackers can change or manipulate the SQL query, and this can lead to unauthorized access to resources and also perform different malicious activities once get access b
4 min read
How to Perform a Bulk Insertion using JDBC?
Performing a bulk insert using JDBC involves using the PreparedStatement interface and addBatch() method. This addBatch() method increases the performance while data is inserted into a database. In this article, we will learn how to perform a bulk insert using JDBC. Approach:For this, we need to create a connection with the database by using the Co
4 min read
How to Execute a SQL Query Using JDBC?
Java programming provides a lot of packages for solving problems in our case we need to execute SQL queries by using JDBC. We can execute a SQL query in two different approaches by using PreparedStatement and Statement. These two interfaces are available in java.sql package. When comparing both of them the PreparedStatement approach is secure. Appr
4 min read
Practice Tags :