Sqlite Update query data in database not updating java gui application - java

Guys i am trying to update data into my database I have already created insert and a delete option but after creating this update query my data is not being updating in database so i request for your help please help me my problem is in video and tutorial available online the data is updating using an where statement in which they use a integer datatype but my database don't have any integer field i have only string field and data is not being updated please help the code of update button is posted below enter code here
JButton ud_btn_Update = new JButton("Update");
ud_btn_Update.setFont(new Font("Tahoma", Font.BOLD, 20));
ud_btn_Update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try { String query="update Customers set "
+ "Name='"+ud_tf_Name.getText()+"' "
+ ",Address='"+ud_tf_Address.getText()+"' "
+ ",Gstin='"+ud_tf_Gstin.getText()+"' "
+ ",Discount='"+ud_tf_Discount.getText()+"' "
+ ",State='"+ud_tf_State.getText()+"' "
+ ",StateCode='"+ud_tf_StateCode.getText()+"' "
+ " where Name='"+ud_tf_Name.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Updated!");
pst.close();
} catch(Exception e4) {
e4.printStackTrace();
}

Your code seems syntactically correct and it should work if the table exists and the table and column names are not misspelled.
What may cause the code to not update the row in the table is the where clause.
This value:
ud_tf_Name.getText()
is obviously the new name that you want to replace the old value in the column name, right?
So, it does not exist in the table and the where clause does not return any row and nothing is updated.
You must save the old name in a string variable, say oldname and use it in the where clause:
............................................
+ " where Name='"+oldname+"' ";
Also you must learn to use parameters with the prepared statements to create safer code.

Related

Java Result Set is not working with pre-scripted SQL

My Java program will not show or work with the SQL values that have already been put into the table prior to working with it in Eclipse.
What I mean is that I can add values to the table and it will tell me if I am adding the same values again, however it will lock up when I am trying to use a value that was already on the table that I put in through SQL.
I am at a loss for words and I can not understand why this is happening. I just need it to tell me that the value exists for the values that were already there. Here is my code:
public void addCourse(Statement st){ //**********This function adds a course to the database.
String courseCode, courseTitle;
int entriesChanged;
try {
System.out.println("Please enter a course code you would like to add: ");
courseCode = scan.next().toUpperCase();
ResultSet rs = st.executeQuery("select * from Course where code = '" + courseCode + "'");
if (rs.next()) {
System.out.println("This course code already exists, please
try again.");
} else {
System.out.println("Please enter the title for the course: ");
courseTitle = scan.next().toUpperCase();
entriesChanged = st.executeUpdate("Insert into Course values
('" + courseCode + "','" + courseTitle + "')");
System.out.println("You just added " + entriesChanged + "
entries to the course list.");
}
rs.close(); //**********Closed the result set in this function.
} catch (SQLException e) {
System.out.println("There was an error during runtime, Error: " +
e.getMessage());
}
Here is my connection statement that I share through the Driver.java class:
try (Connection conn
=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe",
"system", Chicken1") //connect oracle
) {
Statement st = conn.createStatement();
When I said "it locks up", I meant that it asks for the user to enter the title of the course once you enter a course code that already existed on the pre-written SQL table and then it just lets you type endlessly in the console without continuing the program.
However, if I add a course that does NOT exist on the pre-written table, then it adds it to the database and will not let me re-enter the course code that I entered already.
However, when trying to make the program stop me from entering a course code that exists on the pre-written SQL table, that is when it "locks up".

JTable: display strings with newline characters as multiple lines

I added a JTable in a JFrame using drag and drop in netbeans.
I was able to display the contents of the database but it is not like what i want to display, i want strings with newlines to be display as multiple lines.
i have a code here that query in the sqlite database and then displayed it in the table.
public void Update_table_RFID(JTable x){
try{
String sql = " select RFID as 'RFID Tag', Word, ARF as 'Audio Recording File', "
+ " DateAdded as 'Date Added', TimeAdded as 'Time Added' "
+ " from RFID";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
x.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
but the output i got instead is this:
what do i need to do to display the correct output of the query in the table?

Unable to execute update using email address as primary key in Derby

I looked at these questions and my problem is unique to them.
JDBC Update Statement not working in Netbeans but working in SQL
Why is my JDBC prepared statement update not updating the database?
Whenever I use a valid 'email' to update rows in my user_account table, the statement locks up and then I get the following exception:
java.sql.SQLTransactionRollbackException:
A lock could not be obtained within the time requested
For this input it works fine:
EMAIL:chris
NAME:null
PHONE:null
ADDRESS:null
When I use the real input:
EMAIL:validEmailWants#someDomain.com
NAME:null
PHONE:null
ADDRESS:null
The failure occurs.
[EDIT]
However, the input below works fine:
EMAIL:chris#localhost.com
NAME:null
PHONE:null
ADDRESS:null
So it can't be the special characters in email addresses that are
causing the problem.
I am using a prepared statement so I am pretty sure I don't need to 'escape' any of the special characters in the email address. But I could be wrong.
The method is below:
public boolean setInfo(InfoBean p){
//// NOT USING THE PASSED IN INFOBEAN //////////
//// BECAUSE I HAD TO ISOLATE THE BUG //////////
InfoBean proto = new InfoBean();
//FAIL
proto.setEmail("validEmailWants#someDomain.com");
//PASS
//proto.setEmail("chris#localhost.com");
//PASS
//proto.setEmail("validEmailHasWanted#someDomain.com");
// PASS
//proto.setEmail("validEmailWantsHasWanted#someDomain.com");
System.out.println("EMAIL:" + proto.getEmail());
System.out.println("NAME:" + proto.getName());
System.out.println("PHONE:" + proto.getPhoneNumber());
System.out.println("ADDRESS:" + proto.getAddress());
Connection c = null;
try{
c = this.dataSource.getConnection();
String s = "update user_account "
+ "set name = ?, "
+ "phone = ?, "
+ "address = ?, "
+ "image = ?"
+ "where email = ?";
PreparedStatement ps = c.prepareStatement(s);
if(proto.getName() == null)
ps.setString(1, "");
else
ps.setString(1, proto.getName());
ps.setString(2, proto.getPhoneNumber());
ps.setString(3, proto.getAddress());
BufferedImage image = proto.getImage();
if(image != null){
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outStream);
ps.setBlob(4, new ByteArrayInputStream(outStream.toByteArray()));
}
else{
ps.setNull(4, java.sql.Types.BLOB);
}
ps.setString(5, proto.getEmail());
ps.executeUpdate();
ps.close();
c.close();
return true;
}
catch(Exception e){
System.out.println("\n\n SOME KIND OF EXCEPTION \n\n");
e.printStackTrace();
}
finally{
//System.out.println("\n\n SOME KIND OF EXCEPTION \n\n");
closeConnection(c);
}
return false;
}
The database structure is shown below. The underlined words are the primary keys. The diamonds are relationship sets. Circles are attributes (the column names). The squares are tables.
Below is a printout of the user_account table to compare the passing and failing cases specific attribute values.
[UPDATE]
I ran a test case where I set the fields to something
that was NOT NULL, then set the back again to NULL.
(This was on a different email), and there was
no problems. There seems to be something
about that particular email which is causing the
failure.
I found the problem. I was logging in the user in a separate request (which I forgot about) and not closing the connection properly afterward.
(A simple connection.close() in another method fixed the problem).

Java Update clause not updating sqlite database

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) { } }

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

Categories