how to get the last insert id in java mysql - java

i am creating simple sales system. i have to get the last insert id but i couldn't get the id.when i tried the code i got the error of the console
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
i attached the code below what i tried so far
try{
int lastinsertid=0;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");
String query = " insert into sales_product (product, price)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(query);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet rs = preparedStmt.executeQuery();
if (rs.next()) {
lastinsertid = (int) rs.getLong(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
}
catch(ClassNotFoundException coe)
{
System.out.println("odbc driver not found");
}
catch(SQLException sqe)
{
System.out.println(sqe);
}

You need to add Statement.RETURN_GENERATED_KEYS in con1.prepareStatement(query) that would result that you can get the generated key. You also should use only one of the following methods:
executeQuery
executeUpdate
Because there is no reason, to use booth methods.
After you done that you can get it like that:
...
PreparedStatement preparedStmt = con1.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
if (generatedKeyResult.next()) {
lastinsertid = generatedKeyResult.getInt(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
...

Related

how to insert into mysql database with java

i want to insert inputs i take from user into mysql database the connection is right but the insertion gives me error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near ''u_fname',
'u_lname', 'u_uname', 'u_pass', 'u_age', 'u_adderess') values('20','o'
at line 1
My code is:
public void adduser(User s) {
try {
sql = "insert into users ('u_fname', 'u_lname', 'u_uname', 'u_pass', 'u_age', 'u_adderess')"
+ "values('" + s.getFirstname() + "','" + s.getLastname()
+ "','" + s.getUsername() + "','" + s.getPassword() + "','" + s.getAge() + "','" + s.getAdderss() + "')";
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
if (i > 0) {
System.out.println("ROW INSERTED");
} else {
System.out.println("ROW NOT INSERTED");
}
} catch (Exception e) {
System.out.println(e);
}
}
To insert into mysql, follow these steps-
Create a Java Connection to our example MySQL database. I believe you already took care of it. It will be something like this-
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Create a SQL INSERT statement, using the Java PreparedStatement
syntax. Your PreparedStatement SQL statement will be as following this format-
String sql = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
+ " values (?, ?, ?, ?, ?)";
Set the fields on our Java PreparedStatement object. It will done as-
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, s.first_name);
preparedStmt.setString (2, s.last_name);
preparedStmt.setDate (3, s.date_created);
preparedStmt.setBoolean(4, s.is_admin);
preparedStmt.setInt (5, s.num_points);
Execute a Java PreparedStatement.
preparedStmt.execute();
Close our Java MYSQL database connection.
conn.close();
Catch any SQL exceptions that may come up during the process.
catch (Exception e)
{
System.err.println("Got an exception!");
// printStackTrace method
// prints line numbers + call stack
e.printStackTrace();
// Prints what exception has been thrown
System.out.println(e);
}

Insert query not executing

I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();

Java: error inserting data into MySQL

I am using eclipse to insert data into MySQL, and it is only inserting the last row of the data.
String countryCodeSql = "INSERT INTO session" + "(sessionTimestamp,countryCode,countryName,visitorID)" + "VALUES ('"+timeStamp+"','"+countryCode+"','" + countryName+"','" + visitorID+"')";
myStat.executeUpdate(countryCodeSql);
these are my lines of codes, but I think it should be working fine as the codes below worked and the data were inserted.
String timeStampSql = "INSERT INTO conversation" + "(timestamp)" + "VALUES ('" +timeStamp+"')";
myStat.executeUpdate(timeStampSql);
You can use the preparedStatement to insert data in the database when the data are dynamic. here is an example:
Connection connection = DriverManager.getConnection(DATABASE_URL,USERNAME,PASSWORD);
String query = "INSERT INTO session (sessionTimestamp,countryCode,countryName,visitorID) values(?,?,?,?)";
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString (1, timeStamp);
preparedStmt.setString (2, countryCode);
preparedStmt.setString (3, countryName);
preparedStmt.setString (4, visitorID);
preparedStmt.execute();

string parameter and SELECT prepared statement for sql in java

i have a problem >>
programming language: java
Data base: Mysql database
i write a java code for retrive the record from the database based on the data parameters comping from the method>>
the code is:
public static void Get_patient_data(String Hospital1_ID,String Hospital2_ID {
try {
Connection con = getConnection2();
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender "+
"FROM patientcorepopulatedtable "+
"WHERE PatientID = Hospital1_ID LIMIT 1" );
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while( result.next()) {
System.out.print("the patient Gender is" +
result.getString("PatientGender"));
}
}
catch(Exception e) {
System.out.println("Error"+e);
}
}
As you see the problem is Hospital1_ID parameter .. is coming from the method and the patientID is a column in a table patientcorepopulatedtable ...
the = equal operator doesn't work.
Try this
String query =
"SELECT PatientGender FROM patientcorepopulatedtable "+
" WHERE PatientID = ? LIMIT ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, Hospital1_ID);
preparedStmt.setInt (2, 1);
preparedStmt.executeQuery();
you can do it this way
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender FROM patientcorepopulatedtable "+
"WHERE PatientID = ? LIMIT 1");
statement.setString(1, Hospital1_ID);
ResultSet result = statement.executeQuery();
you can find more info here

Retrieve auto_increment value of multiple rows from MySQL in batch mode

There is a mysql table with primary key as id int auto_increment,
I need to insert multiple rows in batch with multiple insert statement, with autocommit disabled, as following:
SET autocommit=0;
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 1, NOW());
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 2, NOW());
COMMIT;
Is it possible to get each generated id, instead of only the last id.
If yes, when was each id generated, and how to get all the ids via jdbc?
Thx.
If you want to retrieve the AUTO_INCREMENT keys via JDBC you need to use the JDBC features for doing so (RETURN_GENERATED_KEYS and .getGeneratedKeys()), like this:
try (Connection conn = DriverManager.getConnection(myConnectionString, "root", "beer")) {
try (Statement st = conn.createStatement()) {
st.execute(
"CREATE TEMPORARY TABLE dummy (" +
"`id` INT AUTO_INCREMENT PRIMARY KEY, " +
"`NAME` VARCHAR(50), " +
"`size` INT, " +
"`create_date` DATETIME " +
")");
}
conn.setAutoCommit(false);
System.out.println("AutoCommit is OFF.");
String sql = "INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', ?, NOW())";
try (PreparedStatement ps = conn.prepareStatement(
sql,
PreparedStatement.RETURN_GENERATED_KEYS)) {
// first batch
ps.setInt(1, 1); // `size` = 1
ps.addBatch();
ps.setInt(1, 2); // `size` = 2
ps.addBatch();
ps.executeBatch();
System.out.println("First batch executed. The following AUTO_INCREMENT values were created:");
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
conn.rollback();
System.out.print("Transaction rolled back. ");
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
// second batch
ps.setInt(1, 97); // `size` = 97
ps.addBatch();
ps.setInt(1, 98); // `size` = 98
ps.addBatch();
ps.setInt(1, 99); // `size` = 99
ps.addBatch();
ps.executeBatch();
System.out.println("Second batch executed. The following AUTO_INCREMENT values were created:");
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
}
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
}
... which produces the following console output:
AutoCommit is OFF.
First batch executed. The following AUTO_INCREMENT values were created:
1
2
The table contains 2 row(s).
Transaction rolled back. The table contains 0 row(s).
Second batch executed. The following AUTO_INCREMENT values were created:
3
4
5
The table contains 3 row(s).

Categories

Resources