JDBC PreparedStatement example – Insert a record

Here’s an example to show you how to insert a record into table via JDBC PreparedStatement. To issue an insert statement, calls the PreparedStatement.executeUpdate() method like this :


String insertTableSQL = "INSERT INTO DBUSER"
		+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
		+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();

Full example…


package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class JDBCPreparedStatementInsertExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			insertRecordIntoTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void insertRecordIntoTable() throws SQLException {

		Connection dbConnection = null;
		PreparedStatement preparedStatement = null;

		String insertTableSQL = "INSERT INTO DBUSER"
				+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
				+ "(?,?,?,?)";

		try {
			dbConnection = getDBConnection();
			preparedStatement = dbConnection.prepareStatement(insertTableSQL);

			preparedStatement.setInt(1, 11);
			preparedStatement.setString(2, "mkyong");
			preparedStatement.setString(3, "system");
			preparedStatement.setTimestamp(4, getCurrentTimeStamp());

			// execute insert SQL stetement
			preparedStatement.executeUpdate();

			System.out.println("Record is inserted into DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (preparedStatement != null) {
				preparedStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                            DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

	private static java.sql.Timestamp getCurrentTimeStamp() {

		java.util.Date today = new java.util.Date();
		return new java.sql.Timestamp(today.getTime());

	}

}

Result

A record is inserted into a table named “DBUSER”.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
blair
Guest
blair

How to handle Commits and rollbacks???
im using statements not prepared statement..

Cyber
Guest
Cyber

thank you, saved me a lot of time!

Alfaz Jikani
Guest
Alfaz Jikani

Thank You:)

Stefania
Guest
Stefania
Hi! I’ve got a little problem with a query. I have to insert records in the User table. In the database postgres User table joins to JobProfile with the key userId. So when I add a new user, userId is addes in User table and JobProfile. How can I do join in java? I’ve never used it. Can you write the query please? This is my query: String string=”INSERT INTO “User” (“userId”,”name”,”surname”,”mail”,”password”,”status”) Values(?,?,?,?,?,?)”; PreparedStatement ad=db.con.prepareStatement(string); ad.setString(1,user.getUserId()); ad.setString(2,user.getName()); ad.setString(3, user.getSurname()); ad.setString(4, user.getEmail()); ad.setString(5, user.getPassword()); ad.setBoolean(6, user.getStatus()); ad.executeUpdate(); So when I add a new user with this query, the user is added… Read more »
sayed farag sayed mohamed
Guest
sayed farag sayed mohamed

Thanks a lot it’s really useful

Zak
Guest
Zak

will this work in a multithreaded environment ,having simultaneous inserts and if the timestamp column is indexed on the db table .

narvouzi
Guest
narvouzi

how i can insert data from JTextFlield ? please

Mike
Guest
Mike

If possible, could you edit the example to a more realistic case where the ID value is auto-genateated, not known before the insert?

Jake
Guest
Jake

I’ve been referring to your examples quite often lately. Thanks for sharing this great material!

IT JOBS
Guest
IT JOBS

Thanks very useful article for inserting data into DB

sakib
Guest
sakib

Suppose database has different tables.How can i access multiple tables ?

Mirak
Guest
Mirak

Multiple sql querys ?

TSMX
Guest
TSMX

Beautiful example, thanks!

Dhaval
Guest
Dhaval

I was wondering if there was any way to execute the below SQL query

INSERT INTO NEW_table(SELECT * FROM OLD_table where city like 'NEW %');

old table and new table have the same schema

subash
Guest
subash

I’m new to here, i leek u website its very helpful to learn java tutorials
i need a code to upload those details in database
[videoname, title, description, duration of video, image file of video, video or filepath of the video]

Hiep Tran
Guest
Hiep Tran

when i insert data to database have Constraint key other table. i don’t now how to do it. Can you help me, please.

amarjeet kumar
Guest
amarjeet kumar

how can use select query inside insert in PreparpreparedStatement.

ex; if I have used select max(id) from table and pass in preaparestmt for increment of id. I know index is a solution for same. But we cane use select in same or not.