所以我有一个在数据库中查找外键的方法。如果外键不存在,它将在数据库中添加一个条目。现在,在插入新记录后,我正在做的是再次重新查询以获取外键。这是矫枉过正还是这是正确的方法?谢谢
private String getTestType(TestResult testResult) {
String testTypeId = "";
String query = String.format("SELECT id FROM test_types WHERE " +
"name='%s'", testResult.getTestType());
try {
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
} else {
st = con.prepareStatement("INSERT INTO test_types (name, " +
"created_at) VALUES (?, ?)");
st.setString(1, testResult.getTestType());
st.setTimestamp(2, new java.sql.Timestamp(System
.currentTimeMillis()));
st.executeUpdate();
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("There was an issue getting and or creating " +
"test Type");
}
return testTypeId;
}
最佳答案
由于您要向数据库中插入新行,因此您必须执行查询来获取自动增量字段(id)。目前他们的做法是可行的。但查询中几乎没有其他选择:
使用last_insert_id()获取id :
rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");
另一种方法是对表的 id 列执行 MAX
。
我相信这些会比您的查询快得多,因为您在 where 子句中进行字符串比较。
关于Java mysql 执行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22284707/