C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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) {
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			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(q);

			smt.executeUpdate(q);

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

			cn.close();
		}catch(Exception e){
			System.out.println(e);  
		}		
	}
}

Output (In console)

Record Submitted...

Output (In Database)

Insert a record in table using JDBC in Java








COMMENTS