JDBC – Insert, Update and Delete example.

Hello Friends,

This is the simple example for executing the SQL statements to INSERT, UPDATE or DELETE any records from the database using JDBC. In the below code I have explained all the three operations. When we insert, update or delete any records from the database we are updating the database, hence we use the executeUpdate() function with the Statement.

Please take the note that whenever you provide the String/Text values for update then add the values in between ” ” or ‘ ‘. This is mandatory for all the Sting types else the DB will not recognize the values and will throw the error. Following is the code:

package com.JavaExamples;

import java.sql.*;

public class JDBCConnectionExample
{
	public static void main(String[] args)
	{
		System.out.println("MySQL & JDBC Connect Example.");
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "code2java";// Database name
		String driver = "com.mysql.jdbc.Driver";
		String userName = "username";
		String password = "password";
		String dbtime = null;
		try
		{
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url+dbName,userName,password);
			System.out.println("Database Connected");
			Statement stmt = conn.createStatement();

			//For inserting the data into database
			String insertQuery = "INSERT table_name(column_1,column_2,column_3,...) values(value_1,value_2,value_3,...)";
			stmt.executeUpdate(insertQuery);

			//For Updating the particular entity of the table
			String updateQuery = "UPDATE table_name SET column_name1=value_1,column_name2=value_2 WHERE column_name=some_value";
			stmt.executeUpdate(updateQuery);

			//For Deleting the specific row/s in the table
			String deleteQuery = "DELETE FROM table_name WHERE column_name=some_value";
			stmt.executeUpdate(deleteQuery);

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			//This is used for Disconnecting..
			try
			{
				conn.close();
				System.out.println("Database Disconnected");
			}
			catch (SQLException e)
			{
				e.printStackTrace();
				System.out.println("Error while Disconnecting from database");
			}

		}
	}
}

Hope this will help you.
Regards,
Nikhil Naoghare.

2 thoughts on “JDBC – Insert, Update and Delete example.”

  1. You actually make it seem so easy along with your presentation however I to find this topic to be actually one thing which I think I might by no means understand. It kind of feels too complex and very extensive for me. I am looking forward in your subsequent put up, I’ll try to get the cling of it!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top