Why data in my table cannot be not updated? - java

I want to update data from my database using java. I have established my connection successfully and When I am updating the table,the data is not updated in the database.
My SQL is like this ::
UPDATE tbl_Bus SET Bus_locX= 520.0,Bus_locY=220.0 WHERE Bus_ID=1
This statement does not update my table though it's working fine when I am using it directly in sql editor in MS Access.
My tbl_Bus
Bus_ID,Bus_LocX,Bus_LocY,Bus_RouteID
and the corresponding data are 1,1,1,1 even after running my app..
My codes
public boolean update_busLoc(double x,double y,int id)
{
String query="UPDATE tbl_Bus SET Bus_locX= "+ x +",Bus_locY="+y + " WHERE Bus_ID="+id;
System .out.println(query);
if (DB_connection!=null){
try{
statement.execute(query);
return true;
}
catch(SQLException e){
e.printStackTrace();
return false;
}
}
else{
System.out.println("Connection is not set up");
return false;
}
}
I use MS Access 2007
I am able to execute SELECT statements and it is working fine but with update I am having problems..
How do I sort this out?

replace
stmt.execute(query);
with
stmt.executeUpdate(query);

Use executeUpdate instead of execute

Is your connection set to autocommit? This might be the problem

I hope this is help full
Replace execute with executeUpdate
use preparedStatement instead of statement
PreparedStatement pstmt = con.prepareStatement("UPDATE tbl_Bus SET Bus_locX=?,Bus_locY=? WHERE Bus_ID=?");
pstmt.setDouble(1, x);
pstmt.setString(2, y);
pstmt.setInt(3, id);
if (DB_connection!=null){
try{
pstmt.executeUpdate();
return true;
}
catch(SQLException e){
e.printStackTrace();
return false;
}
}
else{
System.out.println("Connection is not set up");
return false;
}

Related

query run successful but database not updated java

I'm trying to add Insertquery in a database. everything is working fine and I'm not getting any error. But data which I inserted in a database is not reflected on a database. In sort, Database is not updated.
try{
Database_Operation db = new Database_Operation();
db.connection();
db.cn.setAutoCommit(false);
db.cn.commit();
PreparedStatement ps1=db.cn.prepareStatement("insert into product values(?,?,?)");
Boolean status = true;
ps1.setString(1,name.getText());
ps1.setString(2, price.getText());
ps1.setString(3, status.toString());
db.cn.close();
JOptionPane.showMessageDialog(this," Data saved ", "succsess" ,1);
}catch(Exception e){
e.printStackTrace();
}
What is wrong here?
Your execution statement is si missing.
You're just forming the query and not executing it.
Before closing your db connection, add this line to your code:
ps1.executeUpdate;
You are missing the execution statement. Add following line before DB close.
ps1.executeUpdate();
You must have an execution method in Database_Operation and execute then just after the initialisation of the prepareStatement like this:
try {
// execute update SQL stetement
ps1.executeUpdate();
System.out.println("Record is updated to DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
you haven't execute the PreparedStatement.Add the below line ps1.execute();
try{
Database_Operation db = new Database_Operation();
db.connection();
db.cn.setAutoCommit(false);
db.cn.commit();
PreparedStatement ps1=db.cn.prepareStatement("insert into product values(?,?,?)");
Boolean status = true;
ps1.setString(1,name.getText());
ps1.setString(2, price.getText());
ps1.setString(3, status.toString());
ps1.execute();
db.cn.close();
JOptionPane.showMessageDialog(this," Data saved ", "succsess" ,1);
}catch(Exception e){
e.printStackTrace();
}

Update sql java doesn't work

I am working on Java Application and trying so hard to update record in SQLite database but it doesn't work .. btw it doesn't give me any exceptions or errors
String sql="update Food_Fresh set available=? where Type_ID =?";
st=con.prepareStatement(sql);
st.setInt(1, 1);
st.setInt(2, num);
st.executeUpdate();
st.close();
What's the problem ?!
UPDATE
yes , the initialization of sql
try{
Class.forName("org.sqlite.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Shatha2012\\Desktop\\Core\\IT\\Graduation Project\\Code\\New folder\\Food\\src\\Food\\Food.sqlite");
JOptionPane.showMessageDialog(null, "DONE");
return con;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
and the committing is set as auto commit
Maybe there are no records in your database with Type_ID = num?
Check the value returned from executeUpdate()
int i = st.executeUpdate();
it will show you the number of records updated

How do you determine if an insert or update was successful using Java and MySQL?

I am using Java to connect to a MySQL database. I am trying to insert or update data into the database.
Even though I am quite sure the insert was successful, it returns false.
According to the "execute" API, the return value is "true if the first result is a ResultSet object; false if it is an update count or there are no results".
How can I determine whether or not my insert or update was successful?
public boolean insertSelections(String selection, String name){
String sql ="INSERT INTO WORKREPORT VALUES (?,?,?,?,?)";
boolean action = false;
try {
PreparedStatement stmt = conn.prepareStatement(sql);
SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
String formatDate = dateFormat.format(new java.util.Date(System.currentTimeMillis()));
java.util.Date mDate = dateFormat.parse(formatDate);
java.sql.Timestamp timeStamp = new java.sql.Timestamp(System.currentTimeMillis());
// Date time= new Date(mDate.getTime());
stmt.setInt(1, Integer.parseInt(getNumberByName(name).trim()));
stmt.setString(2, name);
// stmt.setDate(3, time);
stmt.setTimestamp(3, timeStamp);
stmt.setString(4, selection);
stmt.setString(5, "N/A");
action = stmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return action;
}
Since you are using PreparedStatement you can call executeUpdate() -
int count = stmt.executeUpdate();
action = (count > 0); // <-- something like this.
From the Javadoc (Returns) link above, emphasis added,
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing.
If you want to insert a large number of entries, I would prefer addBatch() and executeBatch().
First of all this you should know :
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
int i = stmt.executeUpdate();
if (i > 0) {
System.out.println("success");
} else {
System.out.println("stuck somewhere");
}
Try this and check it out whether insert is happening or not
If you don't get a exception I think query is went ok.
Or, you might be able to use executeUpdate() (http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeUpdate() )
You can do a select count(*) do validate number of records if you want.
Try this, whether you want to know whether the data is inserted or not , if the record is inserted it return true or else false.
if(action > 0){
return true;
}else{
return false;
}

Re-Execute DB update Query When Exception Occurs

I want to re-execute the query whenever SQLException occurs and sometime I get the Exception of
SQLException occurred... com.mysql.jdbc.exceptions.jdbc4.
MySQLTransactionRollbackExceptionDeadlock
found when trying to get lock; try restarting transaction
My code is below. The database is MySQL InnoDB .. Please suggest...
String sqlquery = "UPDATE tbl_users SET abill=?"
+ " WHERE uid=? AND sms='2'";
PreparedStatement preStatement=null;
try{
con.setAutoCommit(false);
preStatement=con.prepareStatement(sqlquery);
preStatement.setString(1,billpush);
preStatement.setString(2,uid);
preStatement.executeUpdate();
con.commit();
}
catch(SQLException sE)
{
log.error("SQLException occurred... "+sE);
con.rollback();
}
finally {
if (preStatement != null) {
preStatement.close();
}
}
UPDATE tbl_users SET abill=billpush, asms ='2' WHERE uid='uid' AND sms='2' and asms<>'2'
This will prevent the dead lock just add a condition at the end as asms<>'2'. hope this solves the problem.
Simply set a flag to true after your dangerous operation:
bool ok = false;
while (!ok) {
ok = false;
try {
doSomethingFishy();
ok = true;
}
catch(Exception e) {
dealWithError(); // perhaps wait for a short while and increment a "retry" counter
}
}

why does executeUpdate return 1 even if no new row has been inserted?

here is my very simple table (Postgres):
CREATE TABLE IF NOT EXISTS PERFORMANCE.TEST
(
test text NOT NULL UNIQUE
);
if I try to insert a String using the command below FROM the database,everything works as expected, not surprisingly a new row appears in the DB.
insert into performance.test (test) values ('abbbbaw');
However if I want to insert a String through JDBC, nothing gets inserted, although preparedStatement.executeUpdate() always returns 1.
Below is my method that should be working but it does not. Please tell me if I am missing something obvious.
I want to add that I never get any SQLException.
private void storePerformance() {
Connection conn= initializePerformanceConnection();
if (conn!= null) {
PreparedStatement insertPS = null;
try {
insertPS = conn.prepareStatement("insert into performance.test (test) values (?)");
insertPS.setString(1, queryVar);
int i = insertPS.executeUpdate();
LogManager.doLog(LOG, LOGLEVEL.INFO," numberofrows= "+i);
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Inserting query failed = "+queryVar,e);
}finally{
if(insertPS != null){
try {
insertPS.close();
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing PreparedStatement failed = "+queryVar,e);
}
}
try {
conn.close();
} catch (SQLException e) {
LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing performanceConnection failed= "+ queryVar, e);
}
}
}
}
that was missing:
conn.commit();
(after the executeUpdate())
actually a new row was inserted but the DB rolled back immediately.
executeupdate is for a 'update table set column = value so on'. For insert just call execute of PreparedStatement.

Categories

Resources