我想在SQLite数据库中创建一个表,如果不存在的话。有什么办法可以做到吗?如果表存在,我不想删除它,如果不存在,只创建它。
从http://www.sqlite.org/lang_createtable.html:
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
我将尝试为这个非常好的问题增加价值,并在@David Wolever的精彩回答下的一条评论中以@BrittonKerin的问题为基础。想在这里分享,因为我有同样的挑战@BrittonKerin,我得到了一些工作(即只想运行一段代码,如果表不存在)。
# for completeness lets do the routine thing of connections and cursors
conn = sqlite3.connect(db_file, timeout=1000)
cursor = conn.cursor()
# get the count of tables with the name
tablename = 'KABOOM'
cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.
# check if the db has existing table named KABOOM
# if the count is 1, then table exists
if cursor.fetchone()[0] ==1 :
print('Table exists. I can do my custom stuff here now.... ')
pass
else:
# then table doesn't exist.
custRET = myCustFunc(foo,bar) # replace this with your custom logic
推荐文章
- 如何在SQLite中看到表的结构?
- Android中使用的SQLite版本?
- 在SQL Server Management Studio中编辑表后保存更改
- 如何在不复制数据的情况下创建Oracle表的副本?
- Core Data vs SQLite 3
- 如何在SQLITE中删除或添加列?
- 如何解锁SQLite数据库?
- 什么时候SQLiteOpenHelper onCreate() / onUpgrade()运行?
- 如何重命名SQLite数据库表中的列?
- 仅当表不存在时才在SQLite中创建表
- 如何使用现有的数据库与一个Android应用程序
- Java和SQLite
- 在SQL Server中将表从一个数据库复制到另一个数据库
- 插入如果不存在,否则更新?
- 如何设置Sqlite3字符串比较时不区分大小写?