Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - check table existence in sqlite

Tags:

java

sqlite

is there a way to check if the table is already existed. It always prompt me t

[SQLITE_ERROR] SQL error or missing database (table player_record already exist).

this is what i want to do

if(player_record is existing){
  don't create table;
}else{
  create table;
}
like image 363
user3276091 Avatar asked Jul 20 '26 09:07

user3276091


2 Answers

For my project, I created a method that looks like this. Instead of doing a query it uses the database's metadata.

    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;
    }

Here is a class that goes along with it:

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;
    }
}

I then use it like this:

SQL sql = new SQL();
if(sql.tableExists("myTableName")){
    // Table Exists!
}else{
    // Table doesn't exist.
}
like image 130
Get Off My Lawn Avatar answered Jul 21 '26 23:07

Get Off My Lawn


To find table exist or not using query is

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

Execute this and then check name is null or not

like image 38
Anik Islam Abhi Avatar answered Jul 22 '26 01:07

Anik Islam Abhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!