【问题标题】:sqlite3 error: no such table: when checking if table existssqlite3错误:没有这样的表:检查表是否存在时
【发布时间】:2015-06-03 16:01:35
【问题描述】:

我已经阅读了几篇文章,但仍然无法弄清楚这里有什么问题。 我有一个 C++ 包装器来调用 sqlite。我想在创建表之前测试它是否存在,通过阅读check-in-sqlite-whether-a-table-exists,我使用下面的sql语句来检查一个表是否存在

"SELECT name FROM test.db WHERE type='table' AND name='table1';"

主要代码如下:

static int callback(void *db, int argc, char **argv, char **azColName){
  for(int i=0; i<argc; ++i){
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
  }
  return 0;
}

class SqliteAccessor {
public:
open(){ sqlite3_open("test.db", &m_db); }
createTable1(){
  string sql = "CREATE TABLE table1(one TEXT);";
  char *zErrMsg = 0;
  int rc = sqlite3_exec(m_db, sql.c_str(), callback, 0, &zErrMsg);
  if( rc != SQLITE_OK ){
    printf("SQL error: %s", zErrMsg);
    sqlite3_free(zErrMsg);
  }
}     
hasTable1(){
  string sql = "SELECT name FROM test.db WHERE type='table' AND name='table1'";
  char *zErrMsg = 0;
  int rc = sqlite3_exec(m_db, sql.c_str(), callback, 0, &zErrMsg);
  if( rc != SQLITE_OK ){
    printf("SQL error: %s", zErrMsg); // Error: no such table: test.db 
    sqlite3_free(zErrMsg);
  } 
}
private:
sqlite3* m_db;
}

main(){
  SqliteAccessor sql;
  sql.open(); // success;
  sql.createTable1(); // success;
  sql.hasTable1(); // fail
}

我也尝试过使用 cli api:

sqlite3 test.db
sqlite> create table table1(one varchar(10));
sqlite> SELECT * FROM test.db;
Error: no such table: test.db
sqlite> SELECT name FROM test.db WHERE type='table' AND name='table1';
Error: no such table: test.db
// however, if I run .tables, then it is there.
sqlite> .tables
table1

这是同样的错误,但为什么会出现这样的错误?它是最新的 sqlite 合并版本。

【问题讨论】:

    标签: c++ sql sqlite


    【解决方案1】:

    改为查看 sqlite_master。

    SELECT * FROM sqlite_master WHERE name LIKE '%your_table_name%'

    【讨论】:

    • 啊哈,看来我必须从“test.db.sqlite_master”中选择,这个“sqlite_master”是不是一个列出所有表的内置表?
    • 如果我使用“SELECT name FROM sqlite_master WHERE type='table' AND name='table1';”一切都会安好的。但是我该如何指定哪个数据库呢?
    • 您有多个数据库吗?我不确定你是否有可能拥有几个“数据库”
    • 是的。一个正在工作,另一个是保存的备份
    • 所以你必须打开两个不同的连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    相关资源
    最近更新 更多