我遇到了Java问题。我可以插入数据......但是我怎么能得到它?我想我是以错误的方式做到的。有人可以帮助我如何获得vendorNo
?
更新
我已经更改了我的代码,它正在插入数据库。插入后出现问题,因为generatedKeys
是null
。
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;
}
答案 0 :(得分:1)
首先检查您的数据库是否支持使用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);
有一个third重载版本接受要检索的列索引数组,但我对它提出了深刻的建议(通过列名检索对于架构更改更安全......比对不起更安全)。
// Will retrieve VendorNo
stmt = con.prepareStatement(strSql, new int[] {1});
另外,正如@Jan所提到的,请注意正确关闭资源。
答案 1 :(得分:0)
作为seen here,您应该在Statement
而非ResultSet
上尝试使用资源。