来自Java的MySQL数据库查询失败

时间:2013-11-23 08:30:52

标签: java mysql jdbc

我在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;

所以,如果我想插入新食物,我应该这样做:

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

现在这是我的问题......我正在使用JDBC在表格中添加新食物:

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);
 }

但是这会抛出SQL异常,因为MySQL想要这里

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

用“”包围值。是否可以从MySQL服务器接受此查询?

3 个答案:

答案 0 :(得分:3)

sql语句缺少列列表的右括号。

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

请注意,在列出价格列后,我已插入)

答案 1 :(得分:0)

你可以写这样的查询:

public void addFood(Meal f)抛出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);
}

答案 2 :(得分:0)

foodsid是uniqueid和主键,所以它应该是,

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