【问题标题】:rs is always true even when table employee is not present in servlet Database即使 servlet 数据库中不存在表员工,rs 也始终为真
【发布时间】:2016-11-17 16:35:34
【问题描述】:

即使表employee 不存在于servlet 数据库中,rs 也始终为真,仅当数据库中不存在表时才想创建表 什么会SELECT count(*)FROM INFORMATION_SCHEMA.TABLES WHERE(TABLE_SCHEMA = 'servlet') AND (TABLE_NAME = 'employee')" 使用 PreparedStement 执行时将返回,并且当表不存在时以及两种情况下表都存在时,结果存储在 resultSet 中

public class Table {
public static void main(String[] args)
{
Connection con=null;
PreparedStatement pstmt=null;
PreparedStatement pstmt1=null;
PreparedStatement pstmt2=null;
ResultSet rs=null;
String qry="SELECT count(*)FROM INFORMATION_SCHEMA.TABLES WHERE(TABLE_SCHEMA = 'servlet') AND (TABLE_NAME = 'employee')";
String qry1="CREATE TABLE servlet.Employee (" +
            " ID INT(6) NOT NULL AUTO_INCREMENT, " +
            " NAME VARCHAR(50) NOT NULL, " + 
            " Department varchar(20) NOT NULL, " + 
            " Salary DECIMAL(8,2) NOT NULL, " + 
            " PRIMARY KEY (ID))";
String qry2="insert into servlet.Employee values(?,?,?,?)";

Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=passworD");
pstmt=con.prepareStatement(qry);
rs=pstmt.executeQuery();
System.out.println(rs.next());
    if(true==!rs.next()){
    pstmt1=con.prepareStatement(qry1);
    pstmt1.executeUpdate();
    pstmt2=con.prepareStatement(qry2);
    pstmt2.setInt(1,id);
    pstmt2.setString(2, name);
    pstmt2.setString(3, dept);
    pstmt2.setDouble(4, salary);
    pstmt2.executeUpdate();
    }
    else{

    pstmt2=con.prepareStatement(qry2);
    pstmt2.setInt(1,id);
    pstmt2.setString(2, name);
    pstmt2.setString(3, dept);
    pstmt2.setDouble(4, salary);
    pstmt2.executeUpdate();
    }
 }

}

【问题讨论】:

    标签: java mysql database jakarta-ee


    【解决方案1】:

    如果表存在,则值为1,否则为0。所以记录总是存在的。正如文档所说:

    ResultSet.next:将光标向前移动一行。如果光标现在位于一行上,则返回 true;如果光标位于最后一行之后,则返回 false。

    rs.next 将始终返回 true,因为它将光标定位在您案例中的第一条记录上。您需要根据count(*) 的值处理逻辑。你不需要 else 子句,因为你没有做不同的事情。

    if(rs.next())
      int count = rs.getInt(1);
      if (count == 0) {
        pstmt1=con.prepareStatement(qry1);
        pstmt1.executeUpdate();
      }
      pstmt2=con.prepareStatement(qry2);
      pstmt2.setInt(1,id);
      pstmt2.setString(2, name);
      pstmt2.setString(3, dept);
      pstmt2.setDouble(4, salary);
      pstmt2.executeUpdate();
    }
    

    【讨论】:

    • 谢谢,但为什么 rs 总是正确的
    • 是的,我的问题已经解决了,但我无法理解我应用的逻辑有什么问题,因为 (!rs.next()) 当表不存在时为真,它应该只在表不存在,否则其余代码应由您纠正@randominstanceoflivingthing
    • 请重新阅读我关于下一种方法的回答,以了解您的逻辑问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多