Java Update clause not updating sqlite database - java

I am making a GUI and I need to update one column called "OCCURRENCES" whenever a patient needs help. I am using Netbeans (Java). For some reason I am not getting any errors. But My table does not Update. The executeUpdate is returning '0'. I have close all my result set statements and prepared statements at the end of the 'try', 'catch'.Also any other updates like updating from textfields, insertion of new patient and deleting patient from a table is working fine; just having problem with updating this column which initial value I have set to be zero whenever an occurrence happens I would like to call this method to increment value on column. I'm just learning to use sqlite, and I am really confuse please help here is the part of the code I am having problems with, Also it reaches the JOPtionPane message successfully.
try
{
conn = javaConnect.ConnectDB();//Returns Connection
PreparedStatement pst = conn.prepareStatement("UPDATE PEMs SET OCCURRENCES = ? "//1
+ "WHERE ROOM = ?");//2
pst.setInt(1, 1);
pst.setInt(2,1);
pst.executeUpdate();
int updated=pst.executeUpdate(); // get count to see if anything was updated
System.out.println("OCC" + updated);
JOptionPane.showMessageDialog(null, "SUCCESSFULL OCCURRENCE");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error UpdateOccurence :" + e);
e.printStackTrace();`enter code here`
}finally {
try{
rs.close(); pst.close(); }
catch(Exception e) { } }

Related

Displaying data in JTextfield from two different mysql tables

Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.

HSQLDB not saving updates made through Java

I am trying to add records to a table in an HSQL database through Java.
I have an HSQL database I made through OpenOffice, renamed the .odb file to .zip and extracted the SCRIPT and PROPERTIES files (It has no data in it at the moment) to a folder "\database" in my java project folder.
The table looks like this in the SCRIPT file
CREATE CACHED TABLE PUBLIC."Season"("SeasonID" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,"Year" VARCHAR(50))
All fine so far, the database connects just fine in Java with this code:
public void connect(){
try{
String dbName = "database\\db";
con = DriverManager.getConnection("jdbc:hsqldb:file:" + dbName, // filenames prefix
"sa", // user
""); // pass
}catch (Exception e){
e.printStackTrace();
}
}
I have the following code to insert a record into "Season".
public void addSeason(String year){
int result = 0;
try {
stmt = con.createStatement();
result = stmt.executeUpdate("INSERT INTO \"Season\"(\"Year\") VALUES ('" + year + "')");
con.commit();
stmt.close();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(result + " rows affected");
}
I have a final function called printTables():
private void printTables(){
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM \"Season\"");
System.out.println("SeasonID\tYear");
while(rs.next()){
System.out.println(rs.getInt("SeasonID") + "\t\t" + rs.getString("Year"));
}
}catch (Exception e) {
e.printStackTrace(System.out);
}
}
Now if I run this sequence of functions:
connect();
printTables();
addSeason("2010");
printTables();
I get this output:
SeasonID Year
1 rows affected
SeasonID Year
0 2010
Now when I close the program and start it again I get exactly the same output. So the change made during the first run hasn't been saved to the database. Is there something I'm missing?
It's caused by write delay params in hsqldb, by default has 500ms delay synch from memory to files.
So problem is solved when it's set to false
statement.execute("SET FILES WRITE DELAY FALSE");
or set as you like based on your app behaviour.
So my workaround is to close the connection after every update, then open a new connection any time I want to do something else.
This is pretty unsatisfactory and i'm sure it will cause problems later on if I want to perform queries mid-update. Also it's a time waster.
If I could find a way to ensure that con.close() was called whenever the program was killed that would be fine...

Show only one error message inside try catch

Inside my Add button click i have typed some codes which works very well and inside my try catch block i have two JOptionPane messages. 1st message is to say that info has been added sucessfully and the other which is inside the catch block is to say that Client cannot be added twice to the same tour on same date.
When I run this code without any primary key violations it shows the 1st message (which is correct) but also shows the 2nd message as well. It should show only 1st message and stop. But after showing both messages it adds to the database.
When I enter something that will give primary key violation, it shows add successfully message( which is wrong) and then the Error message. It doesnt add to the database.
What am I doing wrong?
Here is my code.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DBConnection db = new DBConnection();
if (txt_name.getText().isEmpty() || txt_escort.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Cannot have empty fields");
} else {
clientID = combo_client.getSelectedItem().toString();
tourID = combo_tour.getSelectedItem().toString();
date = combo_date.getSelectedItem().toString();
escortID = txt_escort.getText();
clientName = txt_name.getText();
try {
query = "INSERT INTO tourRParticipant(ClientID,Name,TourID,StartDate,EscortID) VALUES (?,?,?,?,?)";
PreparedStatement stm = db.getconn().prepareStatement(query);
JOptionPane.showMessageDialog(null, "Added successfully!");
stm.setString(1, clientID);
stm.setString(2, clientName);
stm.setString(3, tourID);
stm.setString(4, date);
stm.setString(5, escortID);
rs = stm.executeQuery();
rs.next();
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR..Client cannot be added to the same tour with the same date");
}
ViewTable();
}
}
First of all, you display the success message JOptionPane.showMessageDialog(null, "Added successfully!"); before executing the update. It should be displayed after the insert statement is executed.
Second of all, you should call executeUpdate not executeQuery, since you are executing an INSERT statement.
stm.executeUpdate();
JOptionPane.showMessageDialog(null, "Added successfully!");
JOptionPane.showMessageDialog(null, "Added successfully!");
should be after
rs = stm.executeQuery();
And as pointed in other answer, stmt.executeUpdate() should be used instead of stmt.executeQuery(). As you are passing an update query to executeQuery() method, it is throwing exception. That's why you are always getting two messages.

how to sum up values from oracle database into java?

I have a java application which is connected to an Oracle database. I have a form where the user enters an ID called COMMUNITY_ID, a start date called START_DATE and an end date called END_DATE.
I want the application to search through the table in database for the entered values, and when the search result is correct I want it to display the sum of total values.
I have three methods; each method is responsible for searching a single text box. For example, the first method total 1 searches for the COMMUNITY_ID, and the second method searches for the START_DATE and the last one searches for the END_DATE.
I get an error message saying the result set is empty or closed. I am not sure why because I dont understand the message clearly.
The following is my code. If anyone has idea how to fix it that, please help me.
public void total3()
{
ResultSet result;
System.out.println("total 3");
String endDate = this.EndTxtBox.getText();
try
{
rs=st.executeQuery("select RECIPT_ID,COMMUNITY_ID,VALUE,START_DATE,END_DATE, ITEM_BOUGHT,REASON from RECIPTS where END_DATE = '" +endDate+"'");
//display();
this.EndTxtBox.setText(rs.getString("END_DATE"));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Searched Failed" + ex);
}
try
{
result = rs=st.executeQuery("select SUM(VALUE)from RECIPTS where END_DATE = '" +endDate+"'" );
//result = rs=st.executeQuery("select RECIPT_ID,COMMUNITY_ID,VALUE,START_DATE,END_DATE, ITEM_BOUGHT,REASON,SUM(VALUE)from RECIPTS group by RECIPT_ID,COMMUNITY_ID,VALUE,START_DATE,END_DATE, ITEM_BOUGHT,REASON ");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Error" + ex);
}
}
Any ideas, please? What is wrong with it?
You're trying to read from the result set before going to its first row:
if (rs.next()) {
endDate = rs.getString("END_DATE");
}
Your code is full of bad practices:
mixing UI code with database access code
catching Exception
selecting a whole lot of rows and columns when you're only interested by one of them
not using prepared statements
using both result and rs for the same thing
not closing statements and result sets
using String variables to store dates
poor and inconsistent indentation

How to catch constraint violation inside the resultset loop?

I was working on a servlet that will generate a unique code and update that in a mySQL database.
Now, in that, I want to catch any exception thrown in case that unique code already exists in the mySQL table and generate a new code and try updating the database. The problem is I want to do this WITHIN the for loop itself. The code is as follows:
try
{
connection = datasource.getConnection();
SQLUpdate = "INSERT INTO Voucher_dump VALUES( '"+unique_code+"','08-10-2011 04:48:48','0')";
PreparedStatement ps1 = connection.prepareStatement(SQLUpdate);
ps1.executeUpdate();
ResultSet r = ps1.getResultSet(); // this is where I'm checking if it's a duplicate
if(r==null)
out.println("This is a duplicate");
else out.println("Updated");
trial12= "08-10-2011 04:48:480.03999855056924717a";
SQLUpdate = "INSERT INTO Voucher_dump VALUES( '"+trial12+"','08-10-2011 04:48:48','0')";
ps1 = connection.prepareStatement(SQLUpdate);
ps1.executeUpdate();
r = ps1.getResultSet();
if(r==null)
out.println("This is a duplicate");
else out.println("Updated");
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
I don't want to wait till the end of the entire loop to catch the SQLException (I have already defined this key in mySQL as primary). The moment, the result comes back as a duplicate entry, I want to re-generate this key and attempt the update again.My output for this particular code is coming blank on my output page (all other parameters are showing correctly). Neither is "This is a duplicate" displayed nor is "Updated". Maybe, ResultSet is not the best way to do it. Could you guys give me some advice on what would be the best way forward ?
Some advice in no particular order:
Close the connection in a finally block.
Close statements individually if you'll be creating many of them before closing the connection. ("Many" is defined by your DBAs.)
Format your code.
Don't use stdout and/or stderr from real code. Pick a logging framework.
Consider using some helper classes to simplify (and correct) your database access, like Spring's JdbcTemplate.
Make sure to include relevant context when you post example code.
Due to #6, I don't know what out is, but I suspect the reason you're not seeing anything is that you're inserting a duplicate value with the first statement, which will cause a SQLException from that line, not at getResultSet(), where you seem to expect it. Since the error is written to stdout, it'll show up in your server logs somewhere, but nothing will be written to out. I'm not sure why you think getResultSet() will return null or not null depending on whether there was a constraint violation. Take a look at the javadoc for that method.
Update: 7. As BalusC points out, never, ever concatenate a string directly into a JDBC Statment. Use PreparedStatment's placeholders and set* methods. For info on SQL injection, see Wikipedia and XKCD.
How about this code?
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName);
System.out.println("Connected to the database");
int i = 1; //get the unique code
boolean isInserted = false;
while (!isInserted) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO test values (?)");
preparedStatement.setInt(1, i);
preparedStatement.executeUpdate();
isInserted = true;
} catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) { //Catch the particular exception which throws error on unique constraint. This may depend on Java/MySQL your version
i++; //get the next unique code
}
}
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (Exception e) {
}
}

Categories