Inserting Data Into Table Using JDBC PreparedStatement?
In this tutorial, you will learn how to use PreparedStatement object to insert data into MySQL table.
In the previous tutorial, we have shown you how to use the PreparedStatement object to update data. When you call the
executeUpdate()
method, you get the number of rows affected. When you insert a record into a table, you may want to get the inserted ID back to the program for further processing. Let’s see how we can do it.
First, as always, you open a new connection to MySQL. You can utilized the utility class
MySQLJDBCUtil
that we developed in the previous tutorial.
Then, you construct an
INSERT
statement with placeholders and create a new PreparedStatement
object by calling the prepareStatement()
method of the Connection
object. You pass the INSERT statement as the first argument and an integer with value Statement.RETURN_GENERATED_KEYS
as the the second argument to the method. The second argument instructs JDBC to give the inserted ID back.
Next, you supply values for placeholders by calling
setYYY()
method of the PreparedStatement
object.
After that, you call the
executeUpdate()
method to execute the INSERT
statement. This method returns the number of rows affected. We check the return value to see if the record has been inserted successfully.
Finally, to get the inserted id, you call the
getGeneratedKeys()
method of the PreparedStatement
object. The method returns a ResultSet
. You just need to get data out of this ResultSet
as follows:
The following is the complete example of inserting data into the
candidates
table and get the inserted ID back.
Let’s run the program.
It shows that you have successfully inserted a new candidate into the
candidates
table with id 134.
In this tutorial, we have shown you how to use PreparedStatement object to insert a new record into a MySQL table and get the inserted ID back for further processing.
0 comments:
Post a Comment