Open In App

Java Program to Insert Details in a Table using JDBC

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Import the database
  2. Load and register drivers
  3. Create a connection
  4. Create a statement
  5. Execute the query
  6. Process the results
  7. Close the connection

Procedure:

  1. 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”.
  2. 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.
  3. 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’,’geeks@email.com’,’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','geeks@email.com','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.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads