Wcrousse
Wcrousse

Reputation: 203

JDBC Database access, insert tupple

I'm trying to insert a tuple into a mySQL database in the following manner.

 String insertString = "INSERT INTO listings(Seller, Title, Close_Time, Price, Condition)"
                + " VALUES('"+par.getSellerName()+"', '"+par.getItemName()+"', "
                +closetime+", "+par.getPrice()+", '"+par.getCondition()+"')";

pst = con.prepareStatement(insertString);
pst.executeUpdate();
ResultSet rs = pst.getGeneratedKeys();

but I keep getting a SQL syntax error. Strangely I don't have a problem if I leave off Condition. In the listings table Condition is a varchar(45) and par.getCondition() returns a String length<45.

I have tried this also like:

pst = con.prepareStatement(
                    "INSERT INTO listings(Seller, Title, Close_Time, Price, Condition)"
                    + "VALUES(?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
pst.setString(1, par.getSellerName());
        pst.setString(2, par.getItemName());
        long closeTime = getTimeMills(par.getTimeOver());
        pst.setLong(3, closeTime);
        pst.setDouble(4, par.getPrice());
        pst.setString(5, par.getCondition());
        pst = con.prepareStatement(insertString);
        pst.executeUpdate();
        ResultSet rs = pst.getGeneratedKeys();

with the same results. I'm sure that I must be doing something stupid, but I'm at a total loss. I've printed out the string before the insert is executed and am unable to find any syntax errors. Any help will be greatly appreciated.

Upvotes: 0

Views: 401

Answers (2)

Guido Simone
Guido Simone

Reputation: 7952

Expanding on the current answer, since "Condition" is a column name, and modification of the table may not be an option, you may be able to get by with quoting Condition in your query - either with backticks or quotes characters as described in the document referenced earlier.

The tradeoff is you lose portability since not every database uses this convention. Renaming the column is the best long term option if possible.

Upvotes: 1

Eugenio Cuevas
Eugenio Cuevas

Reputation: 11078

Condition is a reserved word in mysql: see Reserved words for mysql

Just rename the property and it will execute fine

Upvotes: 1

Related Questions