I want to rollback all records have been inserted to table when exception occurs.
but conInsert.rollback() doesn't work.
Maybe I miss some code?
Here is my code
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(connectionUrl);
//con.setAutoCommit(false);
Statement st = con.createStatement();
String querySelectOrderInTp = "SELECT order_in_tp_id, order_in_tp_qty, order_in_tp_price, order_in_tp_article_tc_id, order_in_tp_warehouse_tc_id, inv_stock_tp_id, inv_stock_tp_qty_available from order_in_tp LEFT JOIN inv_stock_tp on(order_in_tp_warehouse_tc_id=inv_stock_tp_whouse_current_id AND order_in_tp_article_tc_id=inv_stock_tp_article_tc_id AND order_in_tp_price=inv_stock_tp_price) where order_in_tp_pick_up_timestamp = 'A' AND order_in_tp_date = '2013-06-11' GROUP BY order_in_tp_id;";
ResultSet rs = st.executeQuery(querySelectOrderInTp);
String queryUpdateInvStockTp = "INSERT INTO inv_stock_tp (cre_tms,upd_tms,cre_usr,upd_usr,version,usr_act,inv_stock_tp_id,inv_stock_tp_key, inv_stock_tp_whouse_current_id,inv_stock_tp_article_tc_id,inv_stock_tp_qty_available,inv_stock_tp_qty_min,inv_stock_tp_price) VALUES (NOW(),NOW(),'demo2','demo2',1,'A',null,'AAAA',?,?,?,0,2000.0000)";
conInsert = DriverManager.getConnection(connectionUrl);
conInsert.setAutoCommit(false);
ps = conInsert.prepareStatement(queryUpdateInvStockTp);
String queryUpdateOrderInTp = "UPDATE order_in_tp set order_in_tp_pick_up_timestamp = ? WHERE order_in_tp_id = ?";
psUpdate = con.prepareStatement(queryUpdateOrderInTp);
while(rs.next()) {
Integer qty = rs.getInt(7) - rs.getInt(2);
ps.setString(1, rs.getString(5));
ps.setString(2, rs.getString(4));
ps.setString(3, rs.getString(2));
ps.execute();
psUpdate.setString(1, "A");
psUpdate.setString(2, rs.getString(1));
psUpdate.execute();
ps.clearParameters();
psUpdate.clearParameters();
}
conInsert.commit();
} catch (Exception e) {
e.printStackTrace();
if (conInsert != null) {
try {
System.err.print("Transaction is being rolled back");
conInsert.rollback();
} catch (SQLException excep) {
excep.printStackTrace();
}
}
}
I make an exception in last record but all record before it still have been inserted.
By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. I dont know java, but make sure that You have the START TRANSACTION statement, and then COMMIT or ROLLBACK.
Related
Good day ,
While I am trying to update data after inserting new ones in the database,
This message is showing for me
can not issue executeupdate() for selects
I have checked tutorialspoint.com and codejava and the codes for both update and select are the same and the program is issuing the statement above
Here is my codes
String Sql="Select * from training where trainID=? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("traTitle"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
String Sql="Select * from training where traTitle =? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("trainID"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
String Sql= "UPDATE training SET traTitle ='"+ jTextField2.getText()+"', Type = "+(String) jComboBox1.getSelectedItem()+"', SDate = '"+sqlDate+"', Edate = '"+sqlDate2+"', location = '"+jTextField3.getText()+"',provider = '"+(String) jComboBox1.getSelectedItem()+"',related = '"+jTextArea1.getText()+"',benefits = '"+jTextArea2.getText()+"'important = '"+jTextArea3.getText()+"' WHERE trainID = "+jTextField1.getText()+"";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
Statement st = con.createStatement();
int i =ps.executeUpdate();
if (i>0)
{
JOptionPane.showMessageDialog(null, "Data is Saved");
}
else {
JOptionPane.showMessageDialog(null, "Data is not Saved");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
JOptionPane.showMessageDialog(null, e);
}
Any Solution ?
Statement st = con.createStatement();
int i = ps.executeUpdate();
The problem is here. You are creating a new, unused, Statement, and then trying to call executeUpdate() on the previously prepared statement, which was a SELECT.
This would have been avoided by correctly scoping the variables concerned as method-local. None of them should be instance or static members.
Image of my table as it is when I start this program.
What I have is a mostly empty table and I am trying to assign a value to a fixed number of elements. The column I am trying to edit is "Geschlecht" and the number of rows I want to edit is "copyMaen" (~50.000 entries). I would like to only select the rows where the value of "Geschlecht" was NULL before and I would like to select the rows randomly.
I am using SQLite through a JDBC driver.
This is the first time for me working with sql. This is how I tried to do it.
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Geschlecht FROM individuen WHERE Geschlecht IS NULL;");
PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen");
while (copyMaen != 0) {
if (rs.getRowId((int) (Math.random() * ReadCSV.sumBev)) == null) {
ps.setInt(2, 0);
ps.executeUpdate();
copyMaen--;
}
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
Obviosly this throws me Errors and I am not really sure how to go on from there. Could somebody point me in the right direction?
For anybody interested this is the solution:
try {
Statement stmt = DBController.connection.createStatement();
String select = "SELECT ID FROM individuen WHERE Geschlecht is NULL ORDER BY RANDOM()" +
" LIMIT " + Integer.toString(copyMaen);
ResultSet rs = stmt.executeQuery(select);
PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen set Geschlecht = ? WHERE ID = ?;");
// rs.beforeFirst();
int count = 0;
while (rs.next()) {
ps.setInt(1, 0);
ps.setInt(2, rs.getInt(1));
ps.addBatch();
if (count%100==0) {
System.out.println(count);
}
count++;
}
DBController.connection.setAutoCommit(false);
ps.executeBatch();
DBController.connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
Try this,
Below update query is enough for update all row where Geschlecht is
null.
try {
Statement stmt = DBController.connection.createStatement();
String updateTableSQL = "UPDATE individuen set Geschlecht = ? where Geschlecht IS NULL";
PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setString(1, "0"); // set zero where Geschlecht null found
// execute update SQL stetement
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.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.
I am inserting a new row in db, there is no exception in the console. But the row is not inserted into the table.
String name = request.getParameter("name");
String city = request.getParameter("city");
String country = request.getParameter("country");
String query = "INSERT INTO `test`.`student`(Name,City,Country)VALUES(?,?,?);";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1,name);
ps.setString(2,city);
ps.setString(3,country);
ps.executeUpdate();
ps.close();
No need of casting the PreparedStatement again in connecting the query. It should be like
Connection conn = getDBConnection();
PreparedStatement ps = con.prepareStatement(query);
Remove the ; from the query inside the doublequotes
Prefer concatenation operator ( + sign) while using single quotes inside double quoted strings in the query
Here is a sample code that I have tested and working fine. Compare it with your code to know what you are doing wrong.
public void insertRowToDB(int staffID, String first_name, String last_name, int department_ID) {
Connection dbConnection = null;
try {
dbConnection = DatabaseConnection.getconnection();
if (!dbConnection.isClosed()) {
String sql = "INSERT INTO staff (staffID,first_name,last_name,department_ID) VALUES(?,?,?,?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
statement.setInt(1, staffID);
statement.setString(2, first_name);
statement.setString(3, last_name);
statement.setInt(4, department_ID);
statement.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (dbConnection!=null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
}
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
A priori view of your code, there is no the commit statement.
You need to perform this statement right before the ps.close() line.
Best regards!
I'm want to delete a person from the database "person" on a given id. It works if I don't use Prepared Statement (the first 5 unmarked lines of code in the try-statement).
But when I try to do it using Prepared Statement it does not work, and I canĀ“t figure out why?
The application gets stuck on prepStatement.executeUpdate();
Therefore I can't even see the value of executeUpdate (if I want to se how many Changes that are made).
I have a similar method, addPerson, where Prepered Statement works perfect. This really confuses me...
I appreciate your help.
private void removePerson() {
int id = Integer.parseInt(idField.getText());
PreparedStatement prepStatement = null;
try {
*/* Statement statement = connection.createStatement();
String sql = "DELETE FROM person WHERE id = '"+id+"'";
statement.executeUpdate(sql);
System.out.println("Person removed from database...");
ResultSet result = statement.executeQuery(sql);
*/*
String sql = "DELETE FROM person WHREE id = ?";
prepStatement = connection.prepareStatement(sql);
prepStatement.setInt(1, id);
prepStatement.executeUpdate();
System.out.println("Person removed from database...");
}
catch (SQLException se) {
se.toString();
}
finally {
try {
prepStatement.close();
}
catch (SQLException ex) {
ex.toString();
}
}
}