ios*_*ios 6 sql database sqlite
当且仅当表中不存在相同的列时,如何在SQLite表中添加列?
使用ALTER TABLE我能够创建一个新列,但想知道如何检查表中是否已存在该列?
如果表不包含列,SQLite会返回类似"no such column:foo"的错误:
select foo from yourTable limit 1
Run Code Online (Sandbox Code Playgroud)
您还可以获取create-table语句:
select sql from sqlite_master where tbl_name = 'YourTableName'
Run Code Online (Sandbox Code Playgroud)
然后解析结果,查找列名.我不知道查询指定表的列列表的优雅方法,尽管可能存在一个.
此外,如果您尝试这样做:
alter table YourTable add column foo {column-def whatever it is}
Run Code Online (Sandbox Code Playgroud)
如果列已存在,则会从SQLite收到错误.你也可以捕获这个错误.
最后你可以这样做:
select sql from sqlite_master
where tbl_name = 'YOURTABLE' and sql like '%"foo" CHAR%'; -- or whatever type
Run Code Online (Sandbox Code Playgroud)
如果指定的表包含查询中用双引号括起的列,并且您指定的类型,则会得到一个结果,否则为空集.指定数据类型可确保LIKE子字符串匹配发生在列名称上.
(我知道)在单个SQLite查询中无法完成所有操作.您必须使用应用程序代码来管理If/Elseness.
检查表是否存在:
select count(*) from sqlite_master where type = 'table' and name = MyTable';
Run Code Online (Sandbox Code Playgroud)
检查表中或现在是否存在列
pragma table_info(thumbnail);
Run Code Online (Sandbox Code Playgroud)
但是,更好的方法可能是基于应用程序维护的模式版本的显式数据库模式更新(例如,从模式版本1到2的特定alter table语句):
pragma user_version;
Run Code Online (Sandbox Code Playgroud)