如果SQLite中不存在ALTER TABLE ADD COLUMN [英] ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

查看:874
本文介绍了如果SQLite中不存在ALTER TABLE ADD COLUMN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们最近需要将列添加到一些现有的SQLite数据库表中。可以使用 更改表添加列 。当然,如果表格已被更改,我们想让它保持不变。不幸的是,SQLite不支持 ALTER TABLE 上的 IF NOT EXISTS 子句。



我们当前的解决方法是执行ALTER TABLE语句并忽略任何重复的列名错误,就像此Python示例(但在C ++中)。



但是,我们通常的设置数据库模式的方法是使用一个.sql脚本,其中包含如果不存在则创建表如果不存在则创建索引语句,可以使用 sqlite3_exec sqlite3 命令执行线工具。我们不能将 ALTER TABLE 放在这些脚本文件中,因为如果该语句失败,则该语句之后的任何内容都不会执行。



我想将表定义放在一个地方,而不要在.sql和.cpp文件之间分割。有没有办法在纯SQLite SQL中编写如果不存在更改表添加列的变通办法?

解决方案

我有99%的纯SQL方法。这个想法是对您的架构进行版本控制。您可以通过两种方式执行此操作:




  • 使用'user_version'pragma命令( PRAGMA user_version )来存储数据库架构版本的增量编号。 / p>


  • 将版本号存储在自己定义的表中。




通过这种方式,在启动软件时,它可以检查数据库架构,并在需要时运行 ALTER TABLE 查询,然后递增存储的版本。到目前为止,这比尝试盲目进行各种更新要好得多,尤其是如果您的数据库多年来增长和更改几次。


We've recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has already been altered, we want to leave it alone. Unfortunately, SQLite doesn't support an IF NOT EXISTS clause on ALTER TABLE.

Our current workaround is to execute the ALTER TABLE statement and ignore any "duplicate column name" errors, just like this Python example (but in C++).

However, our usual approach to setting up database schemas is to have a .sql script containing CREATE TABLE IF NOT EXISTS and CREATE INDEX IF NOT EXISTS statements, which can be executed using sqlite3_exec or the sqlite3 command-line tool. We can't put ALTER TABLE in these script files because if that statement fails, anything after it won't be executed.

I want to have the table definitions in one place and not split between .sql and .cpp files. Is there a way to write a workaround to ALTER TABLE ADD COLUMN IF NOT EXISTS in pure SQLite SQL?

解决方案

I have a 99% pure SQL method. The idea is to version your schema. You can do this in two ways:

  • Use the 'user_version' pragma command (PRAGMA user_version) to store an incremental number for your database schema version.

  • Store your version number in your own defined table.

In this way, when the software is started, it can check the database schema and, if needed, run your ALTER TABLE query, then increment the stored version. This is by far better than attempting various updates "blind", especially if your database grows and changes a few times over the years.

这篇关于如果SQLite中不存在ALTER TABLE ADD COLUMN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆