Java之JDBC创建表之前判断表是否存在

        在使用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 );";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@陆先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值