java - 如果存在符合给定条件的行,如何从 Java 检查数据库?

标签 java database methods

我有表 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/

相关文章:

OOP:应该将多少程序逻辑作为方法封装在相关对象/类中?

java - 生成终端读取其标准输入

java - Clojure:是否可以继承用 :gen-class 定义的类的状态?

mysql - 如何查找mysql RDS实例的CPU利用率

java - Android java SELECT SQLite

java - 如何从 Thread.currentThread().getStackTrace() 获取方法签名(而不是方法名称)?

java - GIF 动画在 JFrame 中播放速度极快

java - 使用 Ansible 在 Amazon Linux EC2 实例上将 fat jar 作为服务运行

database - 多次加入日期维度? - Kimball 关于数据仓库和维度建模的书

sql - 内连接 FROM 子句中的重复表名 (csuser.t2)