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();
}
Related
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);
}
So currently Im trying to do get the auto-incremented primary key by following this answer
Primary key from inserted row jdbc? but apparently the program can't even reach that line and the error appeared on the ps.executeQuery() line after debugging the program, the error it display was only "executeQuery" is not a known variable in the current context. that line, which didn't make sense to me. So how do I go pass this hurdle?
public static int createNewLoginUsers(String newPassword, String newRole) throws SQLException{
Connection conn = DBConnection.getConnection();
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
int id = 0;
try{
String sql = "INSERT into Login(password, role) VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, newPassword);
ps.setString(2, newRole);
ps.executeUpdate();
st = conn.createStatement();
rs = st.executeQuery("SELECT * from Login");
rs.last();
System.out.println(rs.getInt("username"));
id = rs.getInt("username");
rs.close();
} finally{
try{
conn.close();
}catch(SQLException e){
System.out.println(e);
}
}
return id;
}
The part of the method which calls the createNewLoginUsers method
if(newPasstxtfld.getText().equals(retypeNewPasstxtfld.getText())){
//update into database
try {
int username = CreateUsersDAO.createNewLoginUsers( (String) newUserRoleBox.getSelectionModel().getSelectedItem(), newPasstxtfld.getText());
Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
confirmation.setHeaderText("New User Details has been created. Your username is " + username);
confirmation.showAndWait();
} catch (SQLException e) {
}
EDIT:
Databases table added and it's in the provided link below
https://imgur.com/a/Dggp2kc and edit to the codes instead of 2 try blocks in one method i have placed it into a different similar method, updated my codes to the current one I have.
This question already has an answer here:
Closing ResultSet in Java 7 [duplicate]
(1 answer)
Closed 5 years ago.
This question should be simple and it may annoy , but still I got this doubt about closing of Result Set using Java. It should be done for each statement or result set should be closed only in final?
try {
Class.forName(<driver class>);
con = DriverManager.getConnection(
"IP",
"username",
"password");
for(String dealId : items) {
String sql= "SQL Query";
preparedStatement = con.prepareStatement(sql);
rs = preparedStatement.executeQuery();
while(rs.next()) {
count += rs.getInt("total");
}
// Result should be closed here as the statement got executed?
}
System.out.println(count);
if(items.size() == count) {
dealsBelongToTheParty = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
rs.close(); // Or this is right?
preparedStatement.close();
if(!con.isClosed())
con.close();
}
I suggest to use Java 7 try-with-resources
(the code below assumes that the loop var dealId is used in the query)
Class.forName(<driver class>);
try (Connection con = DriverManager.getConnection(
"IP", "username", "password")) {
for(String dealId : items) {
String sql= "SQL Query with " + dealId;
// resources are opened by order
try (PreparedStatement preparedStatement = con.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery()) {
while(rs.next()) {
count += rs.getInt("total");
}
} // resources are implicitly closed in reverse order of open
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(count);
if(items.size() == count) {
dealsBelongToTheParty = true;
}
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
"A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results."
So, you shouldn't worry about closing ResultSet.
This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 6 years ago.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 getting this exception
private String selectCustDetail= "SELECT NAME, PASSWORD, RESID, ACTIVATED, USERTYPE FROM USERDETAIL WHERE MOBILENO=?";
ResultSet rs;
//PreparedStatement preparedStatement = null;
PreparedStatement preparedStatement = null ;
try {
// preparedStatement = con.prepareStatement(selectCustDetail);
preparedStatement = con.prepareStatement(selectCustDetail);
preparedStatement.setString(1, mobileno.toString().trim());
rs = preparedStatement.executeQuery(selectCustDetail );
while (rs.next()) {
// LOGGER.info("fetching - 1" + mobileno);
System.out.println(rs.getString("name"));
userDetai.setName(rs.getString("name"));
userDetai.setPassword(rs.getString("password"));
userDetai.setRestaurant(rs.getString("resId"));
userDetai.setActivated(rs.getString("activated"));
userDetai.setType(rs.getString("userType"));
// LOGGER.info("fetching - 2" + userDetai.getActivated());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//LOGGER.info("Exception - " + e.getMessage());
dinepostcons.msg = dinepostcons.dbError;
return false;
}
finally
{try {
if (preparedStatement != null) {
preparedStatement.close();
}
Change
rs = preparedStatement.executeQuery(selectCustDetail );
to
rs = preparedStatement.executeQuery();
You want the method that invokes your preparedStatement with bind parameters. Not the method from Statement that takes a String without bind parameters.
This question already has answers here:
right syntax to use near '?'
(3 answers)
Closed 7 years ago.
I'm trying to debug my prepared statement in java and I'm stuck on this checkEmail function that I implemented. When I go into debugging and it reaches the setString line, it shows NOT SPECIFIED in place of the '?'. If I hardcode 'findEmail' into the String query it will work and find the email. Here is the piece of code:
public static boolean checkEmail(String findEmail) {
Connection conn = EstablishConnection.conn;
boolean found = false;
try {
String query = "SELECT email FROM customers WHERE email=?";
Logging.debug(query);
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,findEmail);
ResultSet rs = preparedStatement.executeQuery(query);
//Iterate through the results of the query
if (rs.next()) {
found = true;
}
preparedStatement.close();
} catch (Exception e) {
Logging.debug("Exception thrown in CustomerOperations.getCustomerInfo(): " + e.getMessage());
e.printStackTrace();
}
return found;
}
Try to replace this :
ResultSet rs = preparedStatement.executeQuery(query);
With:
ResultSet rs = preparedStatement.executeQuery();
Because you had already pass the query to prepareStatement : conn.prepareStatement(query);