简体   繁体   中英

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.

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

Just rename the property and it will execute fine

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM