在使用JDBC的过程中,有时候无法确定表是否存在,直接创建若存在可能会报错,所以在创建之前可以判断表是否存在,具体如下:
一、判断表是否存在的方法,传入的参数为要判断的表名
public boolean validateTableExist(String tableName){
boolean flag = false;
try {
DatabaseMetaData meta = conn.getMetaData();
String type [] = {"TABLE"};
rs = meta.getTables(null, null, tableName, type);
flag = rs.next();
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
二、使用
如果单张表的时候可以直接传入表名即可;如果多张表的时候不能直接使用循环遍历同时创建表,这样有点小问题,需要结合HashMap对每张表是否存在的情况先保存下来,然后再来遍历HashMap,同时对不存在的表进行创建,这里主要介绍多张表的遍历,具体代码如下。
public void createRecordsTable() throws SQLException {
sql = "select user_id from `user`";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
HashMap<Integer,Boolean> users = new HashMap(); //用来存储每个表是否创建
while (rs.next()) {
int userId = rs.getInt("user_id");
users.put(userId,true); //先全是true
}
//检查表是否存在,遍历集合
for (Integer key : users.keySet()) {
users.put(key,validateTableExist("u"+key));
}
//遍历集合
for (Integer key : users.keySet()) {
if (users.get(key) == false) { //表不存在
UserTable ut = new UserTable(key.toString()); //创建对应的表实例
int cnt = pstmt.executeUpdate(ut.toString());
System.out.println(cnt);
}
}
rs.close();
}
public boolean validateTableExist(String tableName){
boolean flag = false;
try {
DatabaseMetaData meta = conn.getMetaData();
String type [] = {"TABLE"};
rs = meta.getTables(null, null, tableName, type);
flag = rs.next();
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
上面的User实例代码如下:
package table;
public class UserTable {
private String tableName;
public UserTable(String str){
tableName = str;
}
@Override
public String toString() {
return "create table u" + tableName + "(" + "time varchar(50) not null, content varchar(100) not null );";
}
}