SQLITEASSETHELPER正确的升级脚本

时间:2016-05-23 19:56:23

标签: android sqlite

我不明白文档,我担心如果我做错了,我会不小心将我的表放在我的数据库中并破坏原始文件。

https://github.com/jgilfelt/android-sqlite-asset-helper

提及添加值的列。以下代码通过创建者git-hub示例

提供
    -- add a FullNames column to Employees
ALTER TABLE "Employees" RENAME TO 'Employees_ME_TMP';

CREATE TABLE "Employees" 
(
    "EmployeeID" int NOT NULL,
    "LastName" varchar(20) NOT NULL,
    "FirstName" varchar(10) NOT NULL,
    "FullName" varchar(150),
    PRIMARY KEY ("EmployeeID")
);

INSERT INTO "Employees"  
(
    "EmployeeID", 
    "LastName", 
    "FirstName", 
    "FullName"
) 
SELECT 
    "EmployeeID", 
    "LastName", 
    "FirstName", 
    "FirstName" || ' ' || "LastName" 
FROM 
    "Employees_ME_TMP";

DROP TABLE "Employees_ME_TMP";

如果我需要添加两列,然后将一堆值插入到列中,那么这是正确的语法吗?

    -- add a FullNames column and NickName to Employees
ALTER TABLE "Employees" RENAME TO 'Employees_ME_TMP';

CREATE TABLE "Employees" 
(
    "EmployeeID" int NOT NULL,
    "LastName" varchar(20) NOT NULL,
    "FirstName" varchar(10) NOT NULL,
    "FullName" varchar(150),
    "NickName" varchar(150),
    PRIMARY KEY ("EmployeeID")
);

    INSERT INTO Employees (FullName, NickName)
    VALUES ('Tyler Durden','Jack')
    WHERE rowid = 18;

    INSERT INTO Employees (FullName, NickName)
    VALUES ('Donnie Darko','Jake')
    WHERE rowid = 19;

DROP TABLE "Employees_ME_TMP";

1 个答案:

答案 0 :(得分:1)

documentation说:

  

INSERT语句...在现有表中创建一个或多个新行。

您的新表是空的,因此您实际上想要创建行,但这些行中的数据必须来自旧表。所以你必须使用INSERT语句的SELECT形式:

INSERT INTO Employees(EmployeeID, LastName, FirstName)
SELECT EmployeeID, LastName, FirstName FROM Employees_ME_TMP;

INSERT中未提及的其他列将填充其默认值(在本例中为NULL)。 然后,您必须将新值放入这些列中。 使用UPDATE statement

更改行
UPDATE Employees
SET FullName = 'Tyler Durden',
    NickName = 'Jack'
WHERE EmployeeID = 18;

UPDATE Employees
SET FullName = 'Donnie Darko',
    NickName = 'Jake'
WHERE EmployeeID = 19;