java - 即使servlet 数据库中不存在表employee,rs 也始终为true

标签 java mysql database jakarta-ee

即使servlet数据库中不存在表employee,rs也始终为true,仅当数据库中不存在表时才想创建表 以及 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();
    }
 }

}

最佳答案

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

ResultSet.next: Moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row.

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();
}

关于java - 即使servlet 数据库中不存在表employee,rs 也始终为true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40660272/

相关文章:

java - 将 Java Websocket 端点连接到 mySQL

java - 使用java中的 boolean 方法比较一个ArrayList与另一个ArrayList

android - 把每一个字符串都编码成BASE64来存入Mysql好不好?

java - 如何重现磁盘耗尽错误?

java - 从返回枚举的接口(interface)检索数据

c++ - 带有 C++ 的 Mysql 不打印所有数据

mysql - 如何从一个表中选择 2 个字段并将其与另一个表的 1 个字段进行比较

Java:我在从另一个类连接到数据库时遇到问题

SQL查找两列具有相同值的行

sql-server - 无法使用 SSMS 通过 Windows 身份验证连接到本地 SQL Server