How to Insert Record to Database using JDBC in Java

Insert Record to Database using JDBC

This tutorial about, How to Insert Record to Database using JDBC in Java. This example were tested on MySQL database environment and same has been shared in the post.

Environment Details

  • JDK 1.7
  • MySQL Database
  • Eclipse IDE

Table Query

CREATE TABLE employee_details (empId INT, empName VARCHAR(30), empAge INT, empQualification VARCHAR(30), empAddress VARCHAR(50), PRIMARY KEY(empId));

Insert Record to Database using JDBC

Project Structure

Insert Record to Database using JDBC

Right Click on Project -> Go to Properties -> Go to Java Build Path -> Press Add Jars Button -> Select the Jar file from Project Lib Folder -> Click Ok and Close the window.

InsertRecord.java

package com.dineshkrish.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class InsertRecord {

	
	public static void main(String[] args) {
		
		final String DRIVER_NAME = "com.mysql.jdbc.Driver";
		final String CONNECTION_URL = "jdbc:mysql://localhost:3306/ems";
		final String USERNAME = "root";
		final String PASSWORD = "";
		
		final String QUERY = "INSERT INTO employee_details (empId, empName, empAge, empQualification, empAddress) VALUES (?,?,?,?,?)";

		int index = 0;
		
		try {
			
			// Loading the Driver 
			Class.forName(DRIVER_NAME);
			
			// Getting Database Connection Object by Passing URL, Username and Password
			Connection connection = DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD);
			
			PreparedStatement pstmt = connection.prepareStatement(QUERY);
			
			// Setting all Column values based on the Index should start from (1 to n)
			pstmt.setInt(++index, 101);
			pstmt.setString(++index, "Dinesh Krishnan");
			pstmt.setInt(++index, 25);
			pstmt.setString(++index, "MS");
			pstmt.setString(++index, "Chennai, India");
			
			int statusCode = pstmt.executeUpdate(); // Executing the Query for Transaction
			
			if(statusCode > 0) {
				
				System.out.println("Employee Record Inserted Successfully..."); // Success Message
			} else {
				
				System.out.println("Oops Error Occured..."); // Error Message
			}
			
			pstmt.close(); // Closing the Statement Object
			connection.close(); // Closing the Connection Object
			
		} catch (ClassNotFoundException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (SQLException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		}	
	}
	
}

Output

Employee Record Inserted Successfully…

Insert Record to Database using JDBC

References

1. Java SQl Package
2. Java Connection Interface
3. Java PreparedStatement Interface
4. Java DriverManager Class