Home » Java programming language

How to insert records through JDBC in Java?

In this article, we are going to learn how to insert data in a table using JDBC through Java program?
Submitted by Manu Jemini, on October 12, 2017

Prerequisite: How to create a table using JDBC in Java?

First of all we are going to establish a connection using Connection class, for this we are creating an object named cn of this class.

Then, we will prepare a MySQL query statement to insert a record in table named employee, to execute this query statement, we will create an object of Statement class.

Here, we are creating an object named smt of statement class, that will be used to execute query by using executeUpdate() method.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database name: demo
  • Table name: employees
  • Table Fields: empid, empname, dob, city, salary

Java program to insert record in a table using JDBC

import java.io.DataInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class InsertRecord {
	public static void main(String[] args) {
			Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123");
			Statement smt=cn.createStatement();
			DataInputStream KB=new DataInputStream(System.in);
			System.out.print("Enter Employee ID:");
			String eid=KB.readLine();

			System.out.print("Enter Employee Name:");
			String en=KB.readLine();

			System.out.print("Enter Employee Date Of Birth:");
			String ed=KB.readLine();

			System.out.print("Enter Employee City:");
			String ec=KB.readLine();

			System.out.print("Enter Employee Salary:");
			String es=KB.readLine();

			String q="insert into employees values('"+eid+"','"+en+"','"+ed+"','"+ec+"',"+es+")";


			System.out.println("Record Submitted....");

		}catch(Exception e){

Output (In console)

Record Submitted...

Output (In Database)

Insert a record in table using JDBC in Java

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.