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;
}
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.
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With