Java Program to Insert Details in a Table using JDBC
Last Updated :
21 Feb, 2023
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 standard 7 steps are supposed to be followed:
- Import the database
- Load and register drivers
- Create a connection
- Create a statement
- Execute the query
- Process the results
- Close the connection
Procedure:
- Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named “hotelman” and table names are “cuslogin” & “adminlogin”.
- Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating a class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.
- Inserting details in a table using JDBC in the input sample image with parameters as follows
- “cuslogin” table has columns namely -
- name
- password
- email
- address
- phone
- id
- Need is to insert new details inside the "cuslogin” table.
Input sample Image:

3.1: Initialize a string with the SQL query as follows
String sql="insert into cuslogin values('geeksforgeeks','gfg','[email protected]','flat 1','1239087474',10)";
3.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();
3.3: Now, add the SQL query of step 3.1 inside PrepareStatement and execute it as follows
p =con.prepareStatement(sql);
p.execute();
3.4: Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for inserting the details of the customer in 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.
Implementation :
- Example 1 is Connection class of JDBC
- Example 2 is App(Main) class where connection class is used as calling object of Connection class in main class.
Example 1: Connection class
Java
// Java Program to Insert Details in a Table using JDBC
// Connections class
// Importing all SQL classes
import java.sql.*;
public class connection {
// object of Connection class
// initially assigned NULL
Connection con = null;
public static Connection connectDB()
{
try {
// Step 2 is involved among 7 in Connection
// class i.e Load and register drivers
// 2(a) Loading drivers using forName() method
// name of database here is mysql
Class.forName("com.mysql.jdbc.Driver");
// 2(b) Registering drivers using DriverManager
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hotelman",
"root", "1234");
// For DB here (custom sets)
// root is the username, and
// 1234 is the password
// returning the object of Connection class
// to be used in main class (Example2)
return con;
}
// Catch block to handle the exceptions
catch (SQLException | ClassNotFoundException e) {
// Print the exceptions
System.out.println(e);
return null;
}
}
}
Example 2: App/Main Class where the program is compiled and run calling the above connection class object
Java
// Java Program to Insert Details in a Table using JDBC
// Main class
// Step 1: Importing DB classes
// DB is SQL here
import java.sql.*;
// Main/App class of above Connection class
public class GFG {
// MAin driver method
public static void main(String[] args)
{
// Step 2: Showing above Connection class i.e
// loading and registering drivers
// Initially assigning NULL parameters
// to object of Connection class
Connection con = null;
PreparedStatement ps = null;
// Step 3: Establish the connection
con = connection.connectDB();
// Try block to check if exception/s occurs
try {
// Step 4: Create a statement
String sql = "insert into cuslogin values('geeksforgeeks','gfg','[email protected]','flat 1','1239087474',10)";
// Step 5: Execute the query
ps = con.prepareStatement(sql);
// Step 6: Process the results
ps.execute();
}
// Optional but recommended
// Step 7: Close the connection
// Catch block to handle the exception/s
catch (Exception e) {
// Print the exception
System.out.println(e);
}
}
}
Output:

Details added here: “geeksforgeeks” named customer details have been added.
Similar Reads
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 th
3 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 cre
4 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
5 min read
How to Perform a Cascading Delete Using JDBC?
In JDBC, the Cascading Delete Operation is a technique of databases that are used to delete the record parent table. In this article, we will learn How to perform a cascading delete using JDBC. Cascading Delete Using JDBCTo Perform a Cascading Delete using JDBC (Java Database Connectivity), you need
2 min read
Java JDBC Programs - Basic to Advanced
This article provides a variety of programs on JDBC, that are frequently asked in the technical round in various Software Engineering/JAVA Backend Developer Interviews including various operations such as CREATE, INSERT, UPDATE, DELETE and SELECT on SQL Database etc. Additionally, all programs come
3 min read
Java Program to Output Query Results in Tabular Format in JDBC
JDBC (Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like oracle,SQL, etc.it connects the front end for interacting with the users with the backend for storing data. Procedure:Â Creating a databaseConnection classOutpu
5 min read
Java Program to Insert Data from a Database to a Spread Sheet
A database is a persistent collection of data and information which is organized in a particular manner for quick access similarly spreadsheets are another way to store data in tabular form. There are two types of databases of which structured database particularly MySQL database is illustrated here
3 min read
Create a Table in a PDF Using Java
The creation of a table in a PDF using Java is done by installing the document class. While instantiating this class, pass a PdfDocument object as a parameter to its constructor. Then, to feature a table to the document, instantiate the Table class, and add this object to the document using the add(
1 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 perfor
4 min read
How to Get the Insert ID in JDBC?
In Java, for getting the insert ID in JDBC, we have built-in methods like getGeneratedKeys(). This method can be able to get the inserted ID in JDBC. Here, in this article, we have used PreparedStatement for insertion purposes and the SQL Injection attack free also. After performing an insertion ope
3 min read