【发布时间】: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