1

I have this table in MySQL:

CREATE TABLE CanteenMan.Foods (
 id TINYINT PRIMARY KEY AUTO_INCREMENT,
 type ENUM("soup","main","desert") DEFAULT "soup",
 name VARCHAR(30) NOT NULL,
 price FLOAT NULL DEFAULT NULL
)ENGINE = INNODB;

So if i want to insert new food, I should do this:

INSERT INTO Foods(id,type,name,price)
VALUES(NULL,"soup","somename",3.3);

And here is my problem now...I am using JDBC to add new foods in the table:

public void addFood(Meal f) throws ClassNotFoundException, SQLException {

     Class.forName (dbid.driver);
     Connection c = (Connection) DriverManager.getConnection(dbid.url,dbid.user,dbid.pass);
     PreparedStatement ps = (PreparedStatement) c.prepareStatement("INSERT INTO foods(id,type,name,price"
            + "VALUES(NULL,?,?,?)");
     ps.setString(1,f.getType()); // here throws SQLException
     ps.setString(2, f.getName());
     ps.setFloat(3,f.getPrice());

     int rowsInserted = ps.executeUpdate();

     System.out.println("Rows inserted:"+rowsInserted);
 }

But this throws SQL Exception because MySQL wants here

+ "VALUES(NULL,?,?,?)");

to surround the values with "".Is it any way to make this query to be accepted from the MySQL server ?

2
  • We need to see your Meal class, especially what the return value of getType() is. Commented Nov 23, 2013 at 8:32
  • 1
    @chrylis, I think the OP is wrong about the line where the error is Commented Nov 23, 2013 at 8:33

3 Answers 3

3

The sql statement is missing a closing right parenthesis for the list of columns.

PreparedStatement ps = 
(PreparedStatement) c.prepareStatement("INSERT INTO foods(id,type,name,price) "
                + "VALUES(NULL,?,?,?)");

Notice that after the price column is listed, I have inserted ).

Sign up to request clarification or add additional context in comments.

Comments

0

You Can write query like this:

public void addFood(Meal f) throws ClassNotFoundException, SQLException {

 Class.forName (dbid.driver);
 Connection c = (Connection) DriverManager.getConnection(dbid.url,dbid.user,dbid.pass);
 PreparedStatement ps = (PreparedStatement) c.prepareStatement("INSERT INTO foods(id,type,name,price)
        VALUES(NULL,?,?,?)");
 ps.setString(1,f.getType()); // here throws SQLException
 ps.setString(2, f.getName());
 ps.setFloat(3,f.getPrice());

 int rowsInserted = ps.executeUpdate();

 System.out.println("Rows inserted:"+rowsInserted);
}

Comments

0

foods table id is uniqueid and primary key , so it should be like,

PreparedStatement ps = (PreparedStatement) c.prepareStatement("INSERT INTO foods(type,name,price) " + "VALUES(?,?,?)");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.