Sqlite 考虑将其作为删除该项的关键。我正在将收据详细信息保存在表receipt\u barcode中。如果我使用商品条形码作为密钥,则不使用记录id意味着删除收据中相同商品的所有记录

Sqlite 考虑将其作为删除该项的关键。我正在将收据详细信息保存在表receipt\u barcode中。如果我使用商品条形码作为密钥,则不使用记录id意味着删除收据中相同商品的所有记录,sqlite,Sqlite,注意 请理解,这是我写这篇文章时正在使用的代码的复制粘贴。仅作为一个例子,随机复制粘贴对您没有帮助。首先根据您的需要修改此选项 另外,请不要忘记阅读代码中的注释 代码 在类中使用此方法检查是否缺少要添加的列。我们这样做只是为了不重复更改表格收据条形码的过程。 把它作为课堂的一部分提出来。在下一步中,您将看到我们将如何使用它 public boolean是否存在列(SQLiteDatabase mDatabase,String table\u name, 字符串(列名称){ //检查表\u nam

注意

请理解,这是我写这篇文章时正在使用的代码的复制粘贴。仅作为一个例子,随机复制粘贴对您没有帮助。首先根据您的需要修改此选项

另外,请不要忘记阅读代码中的注释

代码

在类中使用此方法检查是否缺少要添加的列。我们这样做只是为了不重复更改表格收据条形码的过程。 把它作为课堂的一部分提出来。在下一步中,您将看到我们将如何使用它

public boolean是否存在列(SQLiteDatabase mDatabase,String table\u name,
字符串(列名称){
//检查表\u name是否具有列\u name
Cursor Cursor=mDatabase.rawQuery(“pragma table\u info(“+table\u name+”),null);
while(cursor.moveToNext()){
if(cursor.getString(cursor.getColumnIndex(“name”)).equalsIgnoreCase(column_name))返回true;
}
返回false;
}
然后,如果您的应用程序的第一次用户尚未退出,则以下代码用于创建表格收据\u条形码。请注意代码中的“如果不存在”。它很重要

//应将mDatabase定义为类成员(全局变量)
//为了便于访问:
//SQLiteDatabase mDatabase=SQLiteDatabase.openOrCreateDatabase(dbfile_path,null);
creation_query=“如果不存在收据条形码,则创建表格(”;
创建\u查询+=“\n记录\u id整数主键自动递增”;
创建\u查询+=“\n rcpt\u id INT(11)不为空,”;
创建\u查询+=“\n条码VARCHAR(255)不为空,”;
创建\u查询+=“\n条形码\u价格VARCHAR(255)默认值(0)”;
创建\u查询+=“\n主键(记录\u id));”;
mDatabase.execSQL(创建\查询);
//这就是关于本页问题的重要部分:
//在旧版本的表格收据条形码中添加缺少的主键记录\u id
如果(!is_列_)存在(mDatabase、“收据条形码”、“记录id”)){
mDatabase.beginTransaction();
试一试{
Log.e(“记录id”、“创建”);
creation_query=“CREATE TEMPORARY TABLE t1_backup(”;
创建\查询+=“记录\ id整数主键自动递增”;
创建查询+=“rcpt\u id INT(11)不为空”;
创建_查询+=“条形码VARCHAR(255)不为空”;
创建_query+=“条形码_price VARCHAR(255)非空默认值(0));”;
mDatabase.execSQL(创建\查询);
creation_query=“插入t1_备份(rcpt_id、条形码、条形码_价格)从收据_条形码中选择rcpt_id、条形码、条形码_价格;”;
mDatabase.execSQL(创建\查询);
创建_query=“删除表格收据_条形码;”;
mDatabase.execSQL(创建\查询);
创建\u query=“创建表格收据\u条形码(”;
创建\查询+=“记录\ id整数主键自动递增”;
创建查询+=“rcpt\u id INT(11)不为空”;
创建_查询+=“条形码VARCHAR(255)不为空”;
创建_query+=“条形码_price VARCHAR(255)非空默认值(0));”;
mDatabase.execSQL(创建\查询);
创建\查询=“插入收据\条形码(记录\ id、rcpt \ id、条形码、条形码\价格)从t1 \ U备份中选择记录\ id、rcpt \ id、条形码、条形码\价格;”;
mDatabase.execSQL(创建\查询);
creation_query=“DROP TABLE t1_backup;”;
mDatabase.execSQL(创建\查询);
mdb.setTransactionSuccessful();
}捕获(异常){
Log.e(“表格收据”bracode、“表格收据”条形码未获得主键(记录id);
异常。printStackTrace();
}最后{
mDatabase.endTransaction();
}

我也遇到了同样的问题,我找到的最佳解决方案是首先创建定义主键的表,然后使用insert into语句

CREATE TABLE mytable (
field1 INTEGER PRIMARY KEY,
field2 TEXT
);

INSERT INTO mytable 
SELECT field1, field2 
FROM anothertable;
根据sqlite关于表创建的介绍,使用生成一个没有约束和主键的新表

但是,文档还指出主键和唯一索引在逻辑上是等价的():

在大多数情况下,通过在数据库中创建唯一索引来实现UNIQUE和PRIMARY KEY约束。(例外情况是INTEGER PRIMARY KEY和PRIMARY KEY on,不带ROWID表)。因此,以下架构在逻辑上是等效的:

CREATE TABLE t1(a, b UNIQUE);

CREATE TABLE t1(a, b PRIMARY KEY);

CREATE TABLE t1(a, b);
CREATE UNIQUE INDEX t1b ON t1(b); 
因此,即使不能通过SQLALTER语法更改表定义,也可以通过使用唯一索引获得相同的主键效果


此外,任何表(不使用rowid语法创建的表除外)都有一个称为“rowid”的内部整数列。根据文档,您可以使用此内部列检索/修改记录表。

此链接()更详细地解释了省略的内容。但我们可以添加新的columns@umesh奇怪的是,在创建表之后不能添加PK,但可以添加索引(
在tableName(columnName)上创建唯一索引pkName)
)当数据库框架(如MS SQL的SMO)真的让你在创建表后添加PK时!@deFreitas请将你的智慧传授给我们。很明显,你想让人们知道你不同意答案或某位评论者所说的话,但是你的评论除了传达明显的意图外,根本没有包含任何信息ty和snark。只是一个警告,如果你做错了,你可以(据我所知)使你的整个数据库无法访问。我在玩ar
sqlite>  create table t(id integer, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t values(1, 'he', 'ha');
sqlite>
sqlite>  create table t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t2 select * from t;
sqlite> .schema
CREATE TABLE t(id integer, col2 varchar(32), col3 varchar(8));
CREATE TABLE t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> drop table t;
sqlite> alter table t2 rename to t;
sqlite> .schema
CREATE TABLE IF NOT EXISTS "t"(id integer primary key, col2 varchar(32), col3 varchar(8));
set databasePath to "~/Documents/Databases/example.db"
set tableOne to "separate" -- Table from which you are pulling data
set tableTwo to "merged" -- Table you are creating
set {tempCol, tempColEntry, permColEntry} to {{}, {}, {}}
set permCol to {"id integer primary key"}

-- Columns are created from single items  AND from the last item of a list
-- {{"a", "b", "c"}, "d", "e"} Columns "a" and "b" will be merged into a new column "c".  tableTwo will have columns "c", "d", "e"

set nonCoal to {"City", "Contact", "Names", {"Address 1", "Address", "address one", "Address1", "Text4", "Address 1"}, {"E-Mail", "E-Mail Address", "Email", "Email Address", "EmailAddress", "Email"}, {"Zip", "Zip Code", "ZipCode", "Zip"}, {"Telephone", "BusinessPhone", "Phone", "Work Phone", "Telephone"}, {"St", "State", "State"}, {"Salutation", "Mr/Ms", "Mr/s", "Salutations", "Sautation", "Salutation"}}

-- Build the COALESCE statements
repeat with h from 1 to count of nonCoal
set aColumn to item h of nonCoal
if class of aColumn is not list then
    if (count of words of aColumn) > 1 then set aColumn to quote & aColumn & quote
    set end of tempCol to aColumn
    set end of permCol to aColumn
else
    set coalEntry to {}
    repeat with i from 1 to count of aColumn
        set coalCol to item i of aColumn as string
        if (count of words of coalCol) > 1 then set coalCol to quote & coalCol & quote
        if i = 1 then
            set end of coalEntry to "TRIM(COALESCE(" & coalCol & ", '') || \" \" || "
        else if i < ((count of aColumn) - 1) then
            set end of coalEntry to "COALESCE(" & coalCol & ", '') || \" \" || "
        else if i = ((count of aColumn) - 1) then
            set as_Col to item (i + 1) of aColumn as string
            if (count of words of as_Col) > 1 then set as_Col to quote & as_Col & quote
            set end of coalEntry to ("COALESCE(" & coalCol & ", '')) AS " & as_Col) & ""
            set end of permCol to as_Col
        end if
    end repeat
    set end of tempCol to (coalEntry as string)
end if
end repeat

-- Since there are ", '' within the COALESCE statement, you can't use "TID" and "as string" to convert tempCol and permCol for entry into sqlite3. I rebuild the lists in the next block.
repeat with j from 1 to count of tempCol
if j < (count of tempCol) then
    set end of tempColEntry to item j of tempCol & ", "
    set end of permColEntry to item j of permCol & ", "
else
    set end of tempColEntry to item j of tempCol
    set end of permColEntry to item j of permCol
end if
end repeat
set end of permColEntry to ", " & item (j + 1) of permCol
set permColEntry to (permColEntry as string)
set tempColEntry to (tempColEntry as string)

-- Create the new table with an "id integer primary key" column
set createTable to "create table " & tableTwo & " (" & permColEntry & "); "
do shell script "sqlite3 " & databasePath & space & quoted form of createTable

-- Create a temporary table and then populate the permanent table
set createTemp to "create temp table placeholder as select " & tempColEntry & " from " & tableOne & ";  " & "insert into " & tableTwo & " select Null, * from placeholder;"
do shell script "sqlite3 " & databasePath & space & quoted form of createTemp

--export the new table as a .csv file
do shell script "sqlite3 -header -column -csv " & databasePath & " \"select * from " & tableTwo & " ; \"> ~/" & tableTwo & ".csv"
CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);
BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;
sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped    
CREATE TABLE mytable (
field1 INTEGER PRIMARY KEY,
field2 TEXT
);

INSERT INTO mytable 
SELECT field1, field2 
FROM anothertable;
CREATE TABLE t1(a, b UNIQUE);

CREATE TABLE t1(a, b PRIMARY KEY);

CREATE TABLE t1(a, b);
CREATE UNIQUE INDEX t1b ON t1(b); 
sqlite>  create table t(id integer, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t values(1, 'he', 'ha');
sqlite>
sqlite>  create table t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite>  insert into t2 select * from t;
sqlite> .schema
CREATE TABLE t(id integer, col2 varchar(32), col3 varchar(8));
CREATE TABLE t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> drop table t;
sqlite> alter table t2 rename to t;
sqlite> .schema
CREATE TABLE IF NOT EXISTS "t"(id integer primary key, col2 varchar(32), col3 varchar(8));