有没有办法检查表是否已经存在。它总是提示我
[SQLITE_ERROR] SQL 错误或缺少数据库(表 player_record 已存在)。
这就是我想要做的
if(player_record is existing){
don't create table;
}else{
create table;
}
Run Code Online (Sandbox Code Playgroud)
对于我的项目,我创建了一个看起来像这样的方法。它不执行查询,而是使用数据库的元数据。
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;
}
Run Code Online (Sandbox Code Playgroud)
这是一个与之相关的类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我像这样使用它:
SQL sql = new SQL();
if(sql.tableExists("myTableName")){
// Table Exists!
}else{
// Table doesn't exist.
}
Run Code Online (Sandbox Code Playgroud)