1

我在使用 Java 时遇到问题。我可以插入数据......但我怎样才能得到它?我想我做错了。有人可以帮助我如何获得vendorNo吗?

更新:

我已经更改了我的代码,它正在插入到数据库中。问题出现在插入之后,因为generatedKeysnull.

public int InsertVendor(String name, String address, String city, String province, String postalCode, String phone, String type, String email) throws SQLException {
    String strSql = "INSERT INTO Vendors (Address1,City,Province,PostalCode,Phone,VendorType,Name,Email)"
            + " values (?,?,?,?,?,?,?,?)";
    PreparedStatement stmt = null;
    ResultSet generatedKeys = null;

    int vendorno = 0;
    Connection con = null;
    //String retName ="Not Found";
    try {
        con = ds.getConnection();
        stmt = con.prepareStatement(strSql);

        stmt.setString(1, address);
        stmt.setString(2, city);
        stmt.setString(3, province);
        stmt.setString(4, postalCode);
        stmt.setString(5, phone);
        stmt.setString(6, type);
        stmt.setString(7, name);
        stmt.setString(8, email);

        int affectedRows = stmt.executeUpdate();
        if (affectedRows == 0) {
            throw new SQLException("Creating user failed, no rows affected.");
        }
        generatedKeys = stmt.getGeneratedKeys();
        if (generatedKeys.next()) {
            vendorno = generatedKeys.getInt(1);
        } else {
            throw new SQLException("Creating user failed, no generated key obtained.");
        }


    } catch (SQLException se) {
        System.out.println("SQL issue" + se.getMessage());
    } catch (Exception e) {
        System.out.println("Other issue" + e.getMessage());
    } finally {

        if (generatedKeys != null) {
            try {
                generatedKeys.close();
            } catch (SQLException se) {
                System.out.println("SQL issue" + se.getMessage());
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException se) {
                System.out.println("SQL issue" + se.getMessage());
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException se) {
                System.out.println("SQL issue" + se.getMessage());
            }
        }
    }
    return vendorno;
}
4

2 回答 2

1

结帐JDBC 标准支持

首先检查您的数据库是否支持使用DatabaseMetaData.supportsGetGeneratedKeys返回生成的密钥。

其次,使用prepareStatement的重载版本之一来指示您要检索生成的列:

// Will retrieve VendorNo
stmt = con.prepareStatement(strSql, new String[] {"VendorNo"});

您还可以使用Statement.RETURN_GENERATED_KEYS检索自动生成的密钥:

stmt = con.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS);

还有第三个重载版本,它接受要检索的列索引数组,但我强烈反对它(按列名检索对架构更改更安全......比抱歉更安全)。

// Will retrieve VendorNo
stmt = con.prepareStatement(strSql, new int[] {1});

此外,正如@Jan 所提到的,请注意正确关闭您的资源。

于 2013-09-21T18:17:31.260 回答
0

如此处所示,您应该在 上而Statement不是在ResultSet.

于 2013-09-21T15:17:02.067 回答