从Java查询MySQL数据库失败

从Java查询MySQL数据库失败,java,mysql,jdbc,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 Fo

我在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服务器接受此查询

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

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

请注意,在列出价格列之后,我插入了

您可以这样编写查询:

公共void addFood(膳食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);
}

foods
table
id
是唯一的主键,所以应该是这样的

PreparedStatement ps=
(准备好的声明)c.准备好的声明(“插入食品(类型、名称、价格)”

+“VALUES(?,?)”;

我们需要查看您的
课程,尤其是
getType()
的返回值。@chrylis,我认为OP在错误所在的行上是错误的