MySQL Syntax Error Exception when executing Update query - java

I'm getting the message
"MySQLSyntaxErrorExcetpion You have an error in your SQL syntax."
I'm following a tutorial online and I don't see what's anything different with my code and the code I'm following. Can anyone point out where I went wrong?
Let me know if additional information is needed.
btn_update.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try{
theQuery("update users set fname = '" + firstNameField.getText() + "', lname = '" + lastNameField.getText() +"', age=" + ageField.getText() + "where id = " + idField.getText());
}
catch(Exception ex)
{
System.out.println(ex);
}
}
});

because you don't have spaces here:
age=" + ageField.getText() + "where id = " + idField.getText());
You need to change it to
age= " + ageField.getText() + " where id = " + idField.getText());
I advice to use PreparedStatement instead of the native way

Add a space in front of " where id = ".
That should work

Use toString() function to convert values to string and then pass them to query, as follow:
firstNameField.getText().toString()

Related

How to update a row of entries in a database (JavaDatabase) that is connected to my JTable?

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.

Using MySQL by Java

I'm coding some database transactions by using java. I'm sending a query using java. I think it has no problem with it. And if I send the query at prompt, it is working.
This method is updating book quantity.
private static void updateBquantity(int bqt, String bname) {
Connection con = makeConnection();
try {
Statement stmt = con.createStatement();
System.out.println(bqt + " " +bname);
//this part is making problem
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where bookname = '" + bname + "';");
System.out.println("<book quantity updated>");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where 도서이름 = '" + bname + "';");
This part is making problem.
Other queries using this form is working.
The compiler says :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'bookname = 'Davinci Code'' at line 1
Help me.
I'm confused with bookname = 'Davinci Code, where is bookname in your query? No matter what, in this query, you missed a blank before where, try this:
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + " where 도서이름 = '" + bname + "';");

Database table update in vaadin

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.

JavaSQLException - ORA-0933: command not properly ended

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

Inserting data into table

Good evening.
I am doing a basic exercise to insert data into an Access Database Table and in the code lies a syntax error which I am struggling to pinpoint.
Was hoping could receive some help with that as to where that Syntax problem lies.
The error reads as follow
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
public void addData(String ID, String name, String address, String type) throws SQLException
{
int rowsadded;
Statement statement = conn.createStatement();
String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + ", " + type + "')";
System.out.println(queryString);
System.out.println(ID + "(ID) added to the database");
rowsadded = statement.executeUpdate(queryString);
System.out.println("Rows updated = " + rowsadded);
}
Method call happens as follow
Insertingdata example;
try
{
example = new Insertingdata();
example.addData("15", "Bob Dylan", "Los Angeles", "Folk");
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(ClassNotFoundException ce)
{
ce.printStackTrace();
}
You missed a couple of single quotes in the query, so address and type were being read as a single value. Replace your queryString line with:
String queryString = "INSERT INTO Artists(ID, Name, Address, Type) VALUES (" + ID + ", '" + name + "', '" + address + "', '" + type + "')";
This should fix the problem.

Categories

Resources