Update sql java doesn't work - java

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

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();
}

Unable to execute the update query in java servlet

I am doing Change password i need to update the old password. based on old password i need to get record and then updating record but here is the problem when i got record i trying to update it shows null in message
My code:
public String ResetPwd(String NewPwd, String name,String oldpwd)
{
String Pass="Select * from Users where Password='"+oldpwd+"' and UserId='"+name+"'";
String UpdateQuery="update Users set Password='"+NewPwd+"' where UserId='"+name+"'";
try{
currentCon = ConnectionManager.getConnection();
st=currentCon.createStatement();
rs = st.executeQuery(Pass);
if(rs.next())
{
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
int i=ps.executeUpdate();
ps.close();
if(i>=1)
{
msg="Password Changed Successfully";
}
}
else{
msg="Old Password Not Match Please Enter Correct Password..!";
return msg;
}
}catch(Exception ex){}
return msg;
}
msg is null because probably some exception is being thrown and it doesn't get set to anything. As #CraigR8806 said don't just ignore the exceptions you catch but print them at least.
The exception being raised is probably SQLException since you are calling
executeUpdate on an already closed preparedStatament in this point
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
ps.executeUpdate();
ps.close();
int i=ps.executeUpdate();
ps.close();
Since there is no reason for a second update change it to:
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
int i=ps.executeUpdate();
ps.close();
as a side note use try with resources as it helps with closing those resources

Insert auto_increment value of the test table to the score table table using a single "update" JButton

Java application to insert student scores and type of test taken
MySql tables tests table and scores tables
I need to update both tables with a single click of the "Update" button. How do I get the tests.test_id value to to inserted on the scores.test_id.
Here is what I have tried so far, however only the test table gets updated.
String subjectCode = SubjectCombo.getSelectedItem().toString(); //gets value selected from subject code JCombobox
String testType = AssesmentCombo.getSelectedItem().toString();//gets value selected from assesment code JCombobox
ResultSet rst = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","edunge","Ihu18om#031988");
st = con.createStatement();
String query4 = "INSERT INTO tests (subject_id, type, test_id) VALUES (?,?,NULL)"; //query to update tests table
ps = con.prepareStatement(query4);
ps.setString(1, subjectCode);
ps.setString(2, testType);
ps.execute();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
if (rst.next()){
JOptionPane.showMessageDialog(null, "Student record updated");
}
} catch (HeadlessException e1) {
JOptionPane.showMessageDialog(null, e1);
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
con.close();
st.close();
rst.close();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
//This successfully updates the test table
I also tried to create another mysql connection on the actionlistener that will take the value of test.test_id and insert it to scores table, with below code.
try {
Connection con2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","edunge","Ihu18om#031988");
Statement st2 = con2.createStatement();
String query5 = "SELECT test_id FROM tests ORDER BY test_id DESC LIMIT 1;";
rst2 = st2.executeQuery(query5);
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
while(rst2.next()){
label.setText(rst2.getString(1)); //used a label to see if the auto_increment values is received.
}
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
Both connection codes to MySQL DB are all in the
"update" actionlistener.
The aim of this is to build a simple student result checker application, for different subjects (with continuous Assessments and Exam) and scores. I would also welcome any advice on building a better MySQL database
The approach to query the generated ID might not always work in case of concurrency, e.g. multiple users using the application at the same time. It depends on the configured concurrency isolation level. If two transactions first both insert the test and then both query the ID one transaction will get the ID of the test that the other transaction inserted.
How to get a generated ID is answered in this post. These are the main things to do according to the post:
PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
...
ResultSet generatedKeys = statement.getGeneratedKeys()
I don't recognize any problems concerning your database schema, but you wouldn't have to think about how to get the ID if you used an ORM-framework like Hibernate.

Error with Oracle 10g auto-incremented sequence

I created a sequence in Oracle 10g because I have to increase case_number field auto_incremently. But I'm getting an error.
private void button_saveandsubmitActionPerformed(java.awt.event.ActionEvent evt) {
con = JavaConnectDB.ConnectDB();
try{
String sql="insert into FIR_form values(case_number_sequence,?,?,?,?,?,?,?,?,?,?,?)";
pst = (OraclePreparedStatement) con.prepareStatement(sql);
pst.setString(1,text_date.getText());
pst.setString(2,text_district.getText());
pst.setString(3,text_subject.getText());
pst.setString(4,text_description.getText());
pst.setString(5,text_cfullname.getText());
pst.setString(6,text_fhname.getText());
pst.setString(7,text_caddress.getText());
pst.setString(8,text_contact.getText());
pst.setString(9,text_suspectfullname.getText());
pst.setString(10,text_suspectaddress.getText());
pst.setString(11,text_suspectdescription.getText());
rs = (OracleResultSet) pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "the FIR has been added successfully!!!");
con.close();
this.dispose();
}
else{
JOptionPane.showMessageDialog(null, "enter all fields appropriately first!!!");
}
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error occured. try again later !!!");
}
}
The field in the table will not auto-populate because you have defined a sequence. You must either reference the sequence.nextval in your insert statement to insert the value, or add a trigger to the table to populate the column from the sequence.
See this post for an example:

Why data in my table cannot be not updated?

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;
}

Categories

Resources