有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

sqlite中存在java检查表

是否有办法检查表是否已经存在。它总是提示我

[SQLITE_ERROR]SQL错误或缺少数据库(table player_记录已存在)

这就是我想做的

if(player_record is existing){
  don't create table;
}else{
  create table;
}

共 (3) 个答案

  1. # 1 楼答案

    SQLite的CREATE TABLE statement具有IF NOT EXISTS子句:

    CREATE TABLE IF NOT EXISTS player_record (
        [...]
    );
    
  2. # 2 楼答案

    对于我的项目,我创建了一个如下所示的方法。它不执行查询,而是使用数据库的元数据

        public boolean tableExists(String tableName){
            connect();
            try{
                DatabaseMetaData md = conn.getMetaData();
                ResultSet rs = md.getTables(null, null, tableName, null);
                rs.last();
                 return rs.getRow() > 0;
            }catch(SQLException ex){
                Logger.getLogger(SQLite.class.getName()).log(Level.SEVERE, null, ex);
            }
            return false;
        }
    

    下面是一个与之配套的类:

    public class SQL{
    
        protected Connection conn = null;
        protected String dbName = "mydatabase.db";
    
        public void connect(){
            if(conn != null){
                return;
            }
            try{
                Class.forName("org.sqlite.JDBC");
                conn = DriverManager.getConnection("jdbc:sqlite:" + dbName);
            }catch(ClassNotFoundException | SQLException e){
                System.err.println(e.getClass().getName() + ": " + e.getMessage());
            }
        }
    
        public boolean tableExists(String tableName){
            connect();
            try{
                DatabaseMetaData md = conn.getMetaData();
                ResultSet rs = md.getTables(null, null, tableName, null);
                rs.last();
                return rs.getRow() > 0;
            }catch(SQLException ex){
                Logger.getLogger(SQLite.class.getName()).log(Level.SEVERE, null, ex);
            }
            return false;
        }
    }
    

    然后我就这样使用它:

    SQL sql = new SQL();
    if(sql.tableExists("myTableName")){
        // Table Exists!
    }else{
        // Table doesn't exist.
    }
    
  3. # 3 楼答案

    要查找表是否存在,请使用查询

    SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';
    

    执行此命令,然后检查名称是否为空