我有表 VIDEO (VideoID int Primary Key, Address Varchar(100))
我想搜索表以查看是否有给定地址的视频。但我不确定这段代码是否有效,是否可以做得更好。
这是我的代码:
public boolean checkIfVideoExist(String address) throws SQLException {
int count = 0;
Statement stmt = connection.createStatement();
ResultSet rset = stmt
.executeQuery("SELECT Count(VideoID) from VIDEO WHERE Address='"
+ address + "'");
if (rset.next())
count = rset.getInt(1);
if (count == 0)
return false;
else
return true;
}
最佳答案
请确保您在 ADDRESS
列上设置了索引。那么您的查询应该运行得很快。
最好使用准备好的语句将地址值传递给查询。并且您应该关闭结果集和语句。
和
if (count == 0)
return false;
else
return true;
看起来有点奇怪。
public boolean checkIfVideoExist(String address) throws SQLException {
int count = 0;
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = connection.prepareStatement(
"SELECT Count(VideoID) from VIDEO WHERE Address=?");
stmt.setString(1, address);
rset = stmt.executeQuery();
if (rset.next())
count = rset.getInt(1);
return count > 0;
} finally {
if(rset != null) {
try {
rset.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
}
}
关于java - 如果存在符合给定条件的行,如何从 Java 检查数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6958502/