【发布时间】:2013-11-23 08:30:52
【问题描述】:
我在 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 服务器被接受?
【问题讨论】:
-
我们需要看看你的
Meal类,尤其是getType()的返回值是什么。 -
@chrylis,我认为 OP 关于错误所在的行是错误的