【问题标题】:MySQL database query from Java fails来自 Java 的 MySQL 数据库查询失败
【发布时间】: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 关于错误所在的行是错误的

标签: java mysql jdbc


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    你可以这样写查询:

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

    【讨论】:

      【解决方案3】:

      foods table id 是 uniqueid 和 primary key ,所以应该是这样的,

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

      【讨论】:

        猜你喜欢
        • 2019-09-27
        • 1970-01-01
        • 1970-01-01
        • 2014-06-04
        • 1970-01-01
        • 2015-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多