This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 6 days ago.
Here is my code:
String sql="INSERT INTO ventas(prefijo,fecha,hora,vtanum,vlrfactura,cambio) VALUES(?,?,?,?,?,?);";
try {
ps=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setString(1, vta.getPrefijo());
ps.setDate(2, vta.getFecha());
ps.setTime(3, vta.getHora());
ps.setInt(4, vta.getVtanum());
ps.setInt(5,vta.getVlrfactura());
ps.setInt(6,vta.getCambio());
ps.execute();
return true;
} catch (SQLException ex) {
Logger.getLogger(OperacionesBD.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
I want get the PK of that sentence and then use it in another statement like this:
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO pagmundimotos.pagos(id_venta,frmpag) VALUES (#last_id_in_table1, '9');
But I don't know how to obtain the last_insert_id in Java.
Use ResultSet object to fetch the GeneratedKeys on Statement
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Inserted ID -" + id); // display inserted record
}
For Oracle :
String key[] = {"ID"}; //put the name of the primary key column
ps = con.prepareStatement(insertQuery, key);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
generatedKey = rs.getLong(1);
}
Related
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 5 years ago.
I'm using H2DB for a litthe cuesheet-database. I'm inserting several records to a table with anj auto-increment field for the primary key ID. For each record I want to know the value of the ID-field after insert, i.e. before committing. How do I get this value?
In short:
use Statement.RETURN_GENERATED_KEYS as second parameter when preparing the insert statement
get ResultSet from statement after insert with .getGeneratedKeys()
get generated id from ResultSet
This should also work when using transactions.
The following example demonstrates this:
try {
// register driver
Class.forName("org.h2.Driver");
// open connection, in-memory database
Connection conn = DriverManager.getConnection("jdbc:h2:mem:");
conn.setAutoCommit(false);
// create table
PreparedStatement createSample = conn.prepareStatement("CREATE TABLE sample (id int not null auto_increment, txt varchar(128))");
createSample.executeUpdate();
createSample.close();
// prepare insert statement
PreparedStatement insertStatement = conn.prepareStatement("INSERT INTO sample (txt) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
// dummy list with texts
List<String> dummyTexts = Arrays.asList("Entry A", "Entry B", "Entry C", "Entry D", "Entry E");
// insert data
for (String dummyText : dummyTexts) {
insertStatement.setString(1, dummyText);
insertStatement.executeUpdate();
// get generated key
ResultSet generatedKeys = insertStatement.getGeneratedKeys();
if ((generatedKeys != null) && (generatedKeys.next())) {
int generatedKey = generatedKeys.getInt(1);
System.out.println("generated key " + generatedKey + " for entry '" + dummyText + "'");
}
}
// commit
conn.commit();
insertStatement.close();
// select data
PreparedStatement selection = conn.prepareStatement("SELECT id, txt FROM sample");
ResultSet selectionResult = selection.executeQuery();
while (selectionResult.next()) {
System.out.println("id: " + selectionResult.getInt(1) + ", txt: '" + selectionResult.getString(2) + "'");
}
selectionResult.close();
selection.close();
// close connection
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
I have below table structure
id msg keyword
-----------------
1 abc ?
2 xyz ?
The above is just an example; however my real table looks like that only. Based on the value of msg field, I need to call an API that would calculate the keywords from the msg and then update the particular record. How can I get the record and update as well, at the same time using Java PreparedStatement?
Also since my database is very large, what would be the efficient way to do it? Below is the code snippet :
public void updateColumns() {
try {
PreparedStatement stmt = null;
ResultSet resultSet = null;
String query = "select * from '" + Constants.tableName + "'";
// How to uypdate the record here by calling my custom API that reads the msg and returns the keywords in the message??
stmt = conn.prepareStatement(query);
stmt.execute();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The idiomatic JDBC solution would be to generate a batch update :
String select = "SELECT id, msg FROM my_table";
String update = "UPDATE my_table SET keyword = ? WHERE id = ?";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(select);
PreparedStatement ps = conn.prepareStatement(update);) {
while (rs.next()) {
ps.setInt(1, rs.getInt(1));
ps.setString(2, MyAPI.calculateKeyword(rs.getString(2));
ps.addBatch();
}
ps.executeBatch();
}
Of course, if you table is very large, you may which to consider every X rows.
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
I want to get the last inserted ID as long. Because the primary key of my table is of long data type.
Here's my code:
Connection connection = null;
Statement statement = null;
try {
String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
System.out.println("LAST INSERTED ID = "+lastInsertedID);
} catch (Exception e) {
e.printStackTrace();
}
I've tested that when the maximum value of integer reaches I get last 1 as last inserted_id.
By the way, I've gone through this post.
Thanks.
try with the following code snippet:
ResultSet rs= statement.getGeneratedKeys();
if (rs.next())
{
System.out.println("Last Inserted ID = "+rs.getLong(1));
}
Here's the full code:
Connection connection = null;
Statement statement = null;
try {
String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs= statement.getGeneratedKeys();
if (rs.next())
{
System.out.println("Last Inserted ID = "+rs.getLong(1));
}
} catch (Exception e) {
e.printStackTrace();
}
I was getting last inserted ID from below code but as I changed it for update it always returns me 0 as last updated ID. Is there any different way to get last Updated id in java using prepared statements?
public static String updateRegistrationInfo(Integer COMPANY_ID, String FIRST_NAME, String LAST_NAME, String MOBILE_NO,
String WORK_EMAIL, String PASSWORD) throws Exception {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Integer last_inserted_id = 0;
String insertTableSQL =
"UPDATE USER_DETAILS SET COMPANY_ID=?,FIRST_NAME=?, LAST_NAME=?, MOBILE_NO=?, WORK_EMAIL=?, PASSWORD=? WHERE WORK_EMAIL=? AND MOBILE_NO=?";
try {
dbConnection = getConnection();
//--USER_ID IS SET TO AUTO INCREMENT PRIMARY KEY
String returnCols[] = { "USER_ID" };
//--INSERTING MEETING DETAILS
preparedStatement = dbConnection.prepareStatement(insertTableSQL, returnCols);
preparedStatement.setInt(1, COMPANY_ID);
preparedStatement.setString(2, FIRST_NAME);
preparedStatement.setString(3, LAST_NAME);
preparedStatement.setString(4, MOBILE_NO);
preparedStatement.setString(5, WORK_EMAIL);
preparedStatement.setString(6, PASSWORD);
preparedStatement.setString(7, WORK_EMAIL);
preparedStatement.setString(8, MOBILE_NO);
// execute insert SQL stetement
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
last_inserted_id = rs.getInt(1);
}
return last_inserted_id.toString();
} catch (SQLException e) {
return e.getMessage() + " ERROR CODE: " + e.getErrorCode();
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
dbConnection = null;
}
}
}
Unlike INSERT which makes new rows, UPDATE operates on existing rows, and therefore it does not generate new row keys. When you make this call
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
last_inserted_id = rs.getInt(1);
}
the result comes back empty, so last_inserted_id remains zero.
The logic behind this is simple: in the INSERT you do not know what the key is going to be, so JDBC lets you retrieve it. In the UPDATE you know what key you are setting - it's the COMPANY_ID, - so you do not need a way to retrieve it back.
So I have a method that looks up a foreign key in a database. If the foreign key does not exist it will add an entry into the database. Now what I am doing from that point after inserting the new record, is re-querying again to get the foreign key. Is this overkill or is this the right way to do this? Thanks
private String getTestType(TestResult testResult) {
String testTypeId = "";
String query = String.format("SELECT id FROM test_types WHERE " +
"name='%s'", testResult.getTestType());
try {
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
} else {
st = con.prepareStatement("INSERT INTO test_types (name, " +
"created_at) VALUES (?, ?)");
st.setString(1, testResult.getTestType());
st.setTimestamp(2, new java.sql.Timestamp(System
.currentTimeMillis()));
st.executeUpdate();
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("There was an issue getting and or creating " +
"test Type");
}
return testTypeId;
}
Since you are inserting a new row into DB, you have to do a query to get back the auto increment field(id). Currently they way you are doing is workable. But there are few alternatives in query:
Obtaining the id using last_insert_id():
rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");
Another approach can be doing the MAX over the id column of the table.
I believe these are will be much faster than your query as you are doing string comparison in where clause.