我在使用 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;
}