rs即使在servlet数据库中不存在表employee时也始终为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();
}
}
}
答案 0 :(得分: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();
}