即使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/