代码之家  ›  专栏  ›  技术社区  ›  Carl

JDBC,MySQL:从PreparedStatement返回行数据

  •  0
  • Carl  · 技术社区  · 16 年前

    public MySQLProcessWriter(Connection con) throws SQLException { 
     String returnNames[] = {"processId","length","vertices"};
     addresser = con.prepareStatement("INSERT INTO addressbook (length, vertices, activity) VALUES (?, ?, ?)", returnNames);
    }
    

    processId 对应于addressbook表中的自动递增列。这样的想法是:我重复插入,我得到一些插入的内容+自动生成的processId。但是,当我尝试执行以下操作时,会得到一个“column not found”SQLException addresser.getGeneratedKeys().getInt("processId"); 在执行准备好的语句之后(在适当的值设置之后)。代码是

    addresser.setInt(1, length);
    addresser.setInt(2, vertices);
    addresser.setDouble(3, activity);
    addresser.executeUpdate();
    int processId = addresser.getGeneratedKeys().getInt("processId");
    

    在更新长度、顶点和活动的循环内。那么…什么给了你?我是否误解了prepareStatement(sqlstring,string[])方法的功能?

    2 回复  |  直到 16 年前
        1
  •  2
  •   delux247    16 年前

    我认为需要对返回的结果集调用next()

    ResultSet keys = addresser.getGeneratedKeys();
    int processId = -1;
    if (keys.next())
    {
      processId = keys.getInt("processId");
    }
    
        2
  •  0
  •   ChssPly76    16 年前

    你必须打电话 next() 方法论 ResultSet getGeneratedKeys() 打电话之前 getInt()

    ResultSet rs = addresser.getGeneratedKeys();
    int processId = 0;
    if (rs.next()) {
      processId = rs.getInt("processId");
    }
    
    推荐文章