I'm trying to update a table in my AccessDB and i'm having a weird problem.
The update executes without throwing any exceptions but the date value is wrong and
everytime i update a record the value always changes to "30/12/1899".
Same thing hapens when i'm trying to insert a new record.
In my DB the Date field is in ShortDate format.
Here is an example of my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
if (jList1.isSelectionEmpty()) {
JOptionPane.showMessageDialog(null, "You have not selected any computer!");
} else {
try {
String sql = "Update SYSTEMS set "
+ " CPU='" + cpuTextField.getText().trim()
+ "', MOBO='" + moboTextField.getText().trim()
+ "', RAM='" + ramTextField.getText().trim()
+ "', GPU='" + gpuTextField.getText().trim()
+ "', HDD='" + hddTextField.getText().trim()
+ "', PSU='" + psuTextField.getText().trim()
+ "', MONITOR='" + monitorTextField.getText().trim()
+ "', KEYBOARD='" + keyboardTextField.getText().trim()
+ "', MOUSE='" + mouseTextField.getText().trim()
+ "', OS='" + osTextField.getText().trim()
+ "', SOFTWARE='" + othersTextArea.getText().trim()
+ "', PURCHASE_DATE=" + df.format(jDateChooser1.getDate())
+ " where SYSTEM_ID='" + jList1.getSelectedValue().toString() + "'";
st = con.prepareStatement(sql);
st.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
JOptionPane.showMessageDialog(null, "Updated");
}
}
In order to figure out what is going wrong, I made a button and when pressed i had
a Message showing the result of df.format(jDateChooser1.getDate()) and
it showed the correct date.
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
JOptionPane.showMessageDialog(null, df.format(jDateChooser1.getDate()));
}
I'm using this component to get the date: JCalendar If that makes any difference.
I dont mind replacing it with a plain TextField, as long as the date is imported correctly.
When using select to retrieve the date from the DB everything goes well.
The problem only occurs when updating/inserting.
The problem likely has to do with the formatting of the SQL query; use a PreparedStatement instead of formatting it manually. Doing so will also decrease the likelihood of errors related to validating user input, including security issues such as SQL injection. For example:
String sql = "Update SYSTEMS set "
+ " CPU=?, MOBO=?, RAM=?"
+ //...
+ ", PURCHASE_DATE=?"
+ " where SYSTEM_ID=?";
PreparedStatement stmt = con.prepareStatement(sql);
int nextField = 1;
stmt.setString(nextField++, cpuTextField.getText().trim());
stmt.setString(nextField++, moboTextField.getText().trim());
stmt.setString(nextField++, ramTextField.getText().trim());
// ...
stmt.setDate(nextField++, jDateChooser1.getDate());
stmt.setString(nextField++, jList1.getSelectedValue().toString());
stmt.executeUpdate();
[Edit] Note that the PreparedStatement#setDate() method requires a java.sql.Date, so you may need to convert the date type returned by your date chooser into one of those, e.g.:
stmt.setDate(nextField++,
new java.sql.Date(jDateChooser1.getDate().getTime()));
Access requires dates to specified in format #MM/dd/yyyy# (including the hash marks). So if you add the # delimiters at the beginning and end of the date string, it should work. As maerics suggested, the best would be to use PreparedStatement, because the JDBC drive will handle converting Java Date to the format Access understands, without you needing to format the value.
Looks like your date format is different from what Access expects.
To get rid of it, use name parameters - as at http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html#supply_values_ps, rather than concatenating the SQL on your own.
Related
I am making a program without knowing much about programming... I used some youtube videos to help me.
My program is made for a chef that can edit users & food and gather ratings and suggestions from the inspector. The chef's section of editing users' details works.
However, the inspector's rating does not as it throws an error: SQLSyntaxException: Encountered "Vegetarian" at line 1, column 65. I believe it is because of getting the rating value (which is int) in a wrong way...
'
public void getConnection(){
try{
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1327/MyApp", "Me", "Me");
mystatObj=myconObj.createStatement();
myresObj=mystatObj.executeQuery("Select * from Me.Food");
tableRateFood.setModel(DbUtils.resultSetToTableModel(myresObj));
}
catch (SQLException e){
e.printStackTrace();
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "update Me.Food set Name = '" + nameText.getText()
+ "',Type = '" + typeText.getText()
+ "', Rating = '" + ratingText.getText()
+ ", 'Vegetarian = '" + vegetarianText.getText()
+ "', ShownOnMenu = '" + showText.getText()
+ "' where Id = " + idText.getText();
//tried the following... did not work either
/*+ " Rating = " + Integer.parseInt(ratingText.getText()));*/
Statement update= myconObj.createStatement();
update.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Updated successfully!");
}
catch(SQLException E){
E.printStackTrace();
}
getConnection();
}
Your forgot a quote in ", 'Vegetarian = '"
Talking about building query strings, you should avoid +-ing values and rely on prepared statements with sql parameters instead. Allows the database to cache the query and avoids sql injection attacks. And spares you formatting headache, think about date values.
I am trying to update the current score in a table on Apache derby. If something already exists then I want it to update or replace the score with new one, and if nothing exists then I want it to insert.
I have written this so far and not sure what to use instead of REPLACE as that is giving me a SQL Error. The WHERE Statement is also giving me an error.
public void saveScore(int score) throws SQLException {
Statement statement = connection.createStatement();
String saveScore = ("REPLACE INTO USER_TABLE (USER_SCORE) VALUES (" + score + ") WHERE USER_TABLE.USER_NAME = '" + gameUsername + "'");
statement.executeUpdate(saveScore);
System.out.println("Score: " + score + " saved for " + gameUsername);
}
Derby doesn't have the REPLACE INTO statement from MySql: use MERGE instead.
See https://db.apache.org/derby/docs/10.13/ref/rrefsqljmerge.html
ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;
I was working with the following code to update my database table with the following code. Database connection is established, no exceptions shown, but my database table is not getting updated.
private void setupSaveButton(){
saveButton.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
try {
String updateQuery = "UPDATE " + MySqlConnectionManager.getDatabaseTableName()
+ " SET BUGID='" + bugIdTextField.getValue()
+ "', USERID='" + userIdTextField.getValue()
+ "', SUBJECT='" + subjectTextField.getValue()
+ "', COMMENT='" + commentTextArea.getValue()
+ "', STATUS='" + statusComboBox.getValue()
+ "', OWNER='" +ownerTextField.getValue()
+ "', PRIORITY='" + priorityComboBox.getValue()
+ "' WHERE DATE='"+dateTextField.getValue()+"'; ";
Connection connection = MySqlConnectionManager.getInstance().getConnection();
if(connection!=null){
Statement stmt = connection.createStatement();
System.out.println("Query " + updateQuery);
stmt.executeUpdate(updateQuery);
}
} catch (SQLException ex) {
Logger.getLogger(BugDetailDisplay.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
I guess you are using DateField for date.
Default date format of MySql is YYYY-MM-DD while your dateTextField.getValue() will return Date Object and default toString representation of Date will be concatenated in your query.So,both formats are different and your query executes successfully but can not detect the row with date you get from dateTextField.You can use SimpleDateFormat to format result of dateTextField.getValue() to allow query to find matching row.
If you are using simple textField than make sure your date format must match with MySql date.
I'm confused about the SQL String query in method below. It shows absolutely correct and despite who rows created in oracle database, threw the following exception: ORA-0933: command not properly ended. I try to find the solution but without result.
What is going wrong? Can you help me?
Thank you in advance and sorry for any bad English.
public void insertMemberAction() {
String query = "INSERT INTO MEMBERS VALUES(" + jMnoTxt.getText() + ", '" +
jLastnameTxt.getText() + "', '" + jFirstnameTxt.getText() + "', '" +
jAddressTxt.getText() + "', '" + jRegistrationDateTxt.getText() + "')";
java.sql.Statement insertStmt;
try {
insertStmt = DvdClubJFrame.con.createStatement();
insertStmt.executeUpdate(query);
insertStmt.close();
} catch (java.sql.SQLException e) {
javax.swing.JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Use PreparedStatements, or escape your parameters using apache common's StringEscapeUtils