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
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'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()
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 + "';");
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.
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.