This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
In MySql, I want to use equivalent of SQL ##IDENTITY and I found this LAST_INSERT_ID(). I found in search that it work fines even if there are different sessions exist. I want to find last ID,in current session. I am using following code.
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/fuel","root", "");
System.out.print("Database is connected !\n");
Statement st = conn.createStatement();
String response = "<food>";
String insertQuery = "INSERT INTO transactions(user_input,fuel_response,execution_time)"+
"VALUES(?,?,?)";
PreparedStatement prepareStatementObj = conn.prepareStatement(insertQuery);
prepareStatementObj.setString(1, "I drank a babyfood juice apple.");
prepareStatementObj.setString(2, response);
prepareStatementObj.setInt(3, 4500);
prepareStatementObj.execute();
String queryForId = "SELECT LAST_INSERT_ID() FROM transactions";
ResultSet rs2 = st.executeQuery(queryForId);
if (!rs2.isBeforeFirst() ) {
System.out.println("No data");
} else {
while ( rs2.next() ) {
int id = rs2.getInt("id");
System.out.println("Last id of this session was..."+id);
}
}
conn.close();
} catch(Exception e) {
System.out.print("Do not connect to DB - Error:"+e);
}
}
Code is working for Insertion but I am not getting last inserted id. It gives following exception.
Column 'id' not found.
I will be thankful to you if you can help.
Modify your select to use alias as id:-
SELECT LAST_INSERT_ID() as id FROM transactions
You're trying to grab a column called id, but there's no such column. When you grab the last inserted ID, you get a column called last_insert_id() instead:
MySQL> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 0 |
+------------------+
1 row in set (0.02 sec)
Easier to grab it by index (use .getInt(int)). This is perfectly safe because you know there will only be one column returned.
You can use below code to get last insert id.
ResultSet rs = prepareStatementObj.getGeneratedKeys();
if(rs.next())
{
last_inserted_id=Integer.toString(rs.getInt(1));
}
Related
This question already has an answer here:
How to retrieve the result of SQL COUNT function from the result set?
(1 answer)
Closed last month.
I want to find the count of the occurence of a name in a mysql table using the query:
select count(*) from employeedetails
How do I fetch the result to a java integer variable?
You can use ResultSet#getInt(int) to return the integer value of a queried column by its ordinal place (i.e., first column is 1, second column is 2, etc):
try (Connection con = /* connect to the database */;
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select count(*) from employeedetails") {
// This query returns at most only one row
if (rs.next()) {
int numEmployees = rs.getInt(1);
// Do something with numEmployees
}
}
This question already has an answer here:
java.sql.sqlexception column not found
(1 answer)
Closed 4 years ago.
i need to get the last id entered in my data base witch is AUTO_INCREMENT so i did this
String Var = "SELECT MAX(id) FROM goupe ; ";
ResultSet vari=st.executeQuery(Var);
while(vari.next()){
nombre = vari.getInt("id");}
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)VALUES('"+name+"','"+familly+"','"+email+"','"+pass+"','"+module+"','"+specialite+"','"+card+"','"+nombre+"');";
st.execute(sql);
but i had this problem Column 'id' not found.
so what should i do to have it right .
I have to say, there are a couple of really easy things you can do to greatly improve your code.
If your latest ID is generated elsewhere, then embed the query directly into the statement such that you don't need to go get it. That will reduce the risk of a race condition.
Use PreparedStatements. Let me ask you this question: What do you suppose is going to happen if one of your user's name is O'Ryan?
Since your code is just a snip, I also will only provide a snip:
int index = 1;
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)" +
"VALUES(?,?,?,?,?,?,?,(SELECT MAX(id) FROM goupe));";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(index++, name);
ps.setString(index++, familyname);
ps.setString(index++, email);
ps.setString(index++, password);
ps.setString(index++, module);
ps.setString(index++, speciality);
ps.setString(index++, card);
int rows = ps.executeUpdate();
if(rows == 1) {
System.out.println("Successfully inserted row");
}
When you execute the query SELECT MAX(id) FROM goupe;, then in the returned table, the column name no longer remains as id.
So, the best approach is to provide a name for the column like below:
SELECT MAX(id) AS maxid FROM goupe;
Then, you can get the value using:
vari.getInt("maxid")
I'm working with my project just for a academic purposes where I encounter a SQL problem. Where the Foreign Key its not getting the value of inserted ID. For me to achieve 2nd Normal Form. I split out in an independent tables. And match them up using the SECTION_ID as foreign keys. Here where I create a two tables.
1st Table
2nd Table
SOURCE CODE:
String inputSectionName = Section_SectionName_TextField.getText();
int inputStudentLimit = Section_Student_Limit_ComboBox.getSelectedIndex();
String inputRoomAssign = Section_Student_Limit_ComboBox2.getSelectedItem().toString();
String inputAdviserAssign = Section_Student_Limit_ComboBox1.getSelectedItem().toString();
String inputSession = Section_Session_Settings_ComboBox.getSelectedItem().toString();
String inputYearLevel = Section_Session_Level_ComboBox.getSelectedItem().toString();
String inputSchoolYear = Section_SchooYear_ComboBox.getSelectedItem().toString();
String insertALLSECTION_LIST = "INSERT INTO ALLSECTIONS_LIST (SECTION_NAME)"
+ "VALUES (?)";
String insertALLSECTIONS_SETTINGS = "INSERT INTO ALLSECTIONS_SETTINGS (SECTION_POPULIMIT,ROOM_ASSGN,ADVISER_ASSIGNED,SESSION_ASSIGNED,YRLEVEL_ASSGN,SCHOOL_YEAR)"
+ "VALUES(?,?,?,?,?,?)";
try (Connection myConn = DBUtil.connect())//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
}//end of try
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTIONS_SETTINGS))//Prepared Statement
{
myPs.setInt(1,inputStudentLimit);
myPs.setString(2, inputRoomAssign);
myPs.setString(3, inputAdviserAssign);
myPs.setString(4, inputSession);
myPs.setString(5, inputYearLevel);
myPs.setString(6, inputSchoolYear);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null, "Insert Successful");
}//end of try
}//end of try
catch(SQLException e)
{
DBUtil.processException(e);
}//end of catch
When I run my query for the 1st Table it gives me output like this.
But when I run my query for the 2nd Table the SECTION_ID column gives a me null value.
Feel free to comment. If I miss something guide me where I go wrong. Thanks.
It looks like you're assuming the SECTION_ID column in your ALLSECTIONS_SETTINGS table will be automatically populated with the last primary-key value that was inserted into the ALLSECTIONS_LIST table. This doesn't happen.
What you need to do instead is to get the value that was automatically generated for the SECTION_ID column in the first PreparedStatement and set it in the second PreparedStatement.
Here's how to modify your first PreparedStatement to obtain the generated SECTION_ID:
int sectionId;
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST, Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
ResultSet generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next()) {
sectionId = generatedKeys.getInt(1);
} else {
throw new SQLException("No generated section ID returned");
}
}
The changes are:
add a new variable sectionId to hold the generated section ID,
add Statement.RETURN_GENERATED_KEYS to the call to prepareStatement on the first line. This tells your database to return the generated value for SECTION_ID.
fetch the generated-keys result-set from the statement and read the section ID out of it..
I'll leave it up to you to modify your second PreparedStatement to set the value for the SECTION_ID column when you insert into ALLSECTIONS_SETTINGS.
Hi i am a newbie to use MySql statements.
This is my Parent table
Name Sell_amt Mrp_amt Cost_amt Goods_Name Goods_Weight Goods_quantity
John 100 90 80 Choclate 1lb 5
samson 100 110 60 mobile 0.5lb 8
James 100 100 70 chair 1lb 5
This is my Child table columns
Name Sell_amt Mrp_amt Special_DealStatus
Now i need to update the child table based on my parent table.
The problem is If (Sell_amt'<'Mrp_amt) then i need to update Special_DealStatus column with 1.
Please suggest,I have googled a lot but couldn't find the answer.
I created a SQL fiddle for you to try out. What you are looking for is this
INSERT INTO Child_Table (`name`, `sellamt`, `mrpamt`, `specialdealstatus`)
SELECT name, sellamt, mrpamt,1
FROM Parent_Table
WHERE sellamt < mrpamt;
here is the SQL fiddle
What this does is inserts the selected values from the Parent_Table into the the Child_Table WHERE sellamt < mrpamt as you asked. It also sets specialdealstatus to one with a static value '1' placed into the SELECT statement.
import java.sql.*;
public class MysqlPreparedStatement
{
public static void main(String[] args)
{
try
{
// create a mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String mySqlServer = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(mySqlServer, "root", "");
// the mysql statement
String query = " INSERT INTO Child_Table (`name`, `sellamt`, `mrpamt`, `specialdealstatus`)
SELECT name, sellamt, mrpamt,1
FROM Parent_Table
WHERE sellamt < mrpamt ";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
catch (Exception e)
{
System.err.println("Throwing an exception!");
System.err.println(e.getMessage());
}
}
}
You could try something like the following with case as Andreas already mentioned.
insert into Child
select Name,Sell_amt,Mrp_amt, case when sell_amt<Mrp_amt then 1 else null end as Special_DealStatus from Parent
This question already has an answer here:
What is wrong with this update query in java?
(1 answer)
Closed 7 years ago.
I am not so into database and I have the following problem in a Java application that have to perform a very simple query that update a field on a table of my DB.
So, the original query is something like this:
UPDATE coda_tx c SET c.FK_STATO = 2 WHERE c.PK_CODA = 62816;
so I have implemented the following Java method that implement the previous query, this one:
public void updateStatus(int pkCoda, int newStatus) {
String sql;
StringBuffer sb = new StringBuffer();
sb.append("UPDATE coda_tx c SET c.FK_STATO = ");
sb.append(newStatus);
sb.append(" WHERE c.PK_CODA = ");
sb.append(pkCoda);
sql = sb.toString();
try {
statment = connection.createStatement();
ResultSet rs = statment.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
My only doubt is related about the section by which the query is performed, this one:
statment = connection.createStatement();
ResultSet rs = statment.executeQuery(sql);
I think that this is wrong because actually there is ResultSet that is an object used to retrieve rows by a SELECT operation. In this case I am updating a field of a specific row and I am not retrieving rows putting theme into a ResultSet object.
So, how can I correctly handle this situation? How have I to perform my query?
Here is how you could do it:
// updateCount contains the number of updated rows
int updateCount = statment.executeUpdate(sql);
You are looking for statement.executeUpdate() which will return the number of rows affected by the update.
int executeUpdate(String sql) throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Reference: http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
If your method recives for example two variables like fkStato and pkCoda, that contains the value you want, you can make a simple query:
int fkStato=2;
int pkCoda=62816;
try
{
// create our java preparedstatement using a sql update query
PreparedStatement ps = conn.prepareStatement(
"UPDATE coda_tx c SET c.FK_STATO = ? WHERE c.PK_CODA = ?;");
// set the preparedstatement parameters
ps.setInt(1,fkStato);
ps.setInt(2,pkCoda);
// call executeUpdate to execute our sql update statement and returns number of rows affected
int updateCount = ps.executeUpdate();
ps.close();
}
catch (SQLException se)
{
// log the exception
throw se;
}