SQLite add Primary Key

前端 未结 11 2438
你的背包
你的背包 2020-11-28 06:07

I created a table in Sqlite by using the CREATE TABLE AS syntax to create a table based on a SELECT statement. Now this table has no primary key b

11条回答
  •  渐次进展
    2020-11-28 06:37

    Introduction

    This is based on Android's java and it's a good example on changing the database without annoying your application fans/customers. This is based on the idea of the SQLite FAQ page http://sqlite.org/faq.html#q11

    The problem

    I did not notice that I need to set a row_number or record_id to delete a single purchased item in a receipt, and at same time the item barcode number fooled me into thinking of making it as the key to delete that item. I am saving a receipt details in the table receipt_barcode. Leaving it without a record_id can mean deleting all records of the same item in a receipt if I used the item barcode as the key.

    Notice

    Please understand that this is a copy-paste of my code I am work on at the time of this writing. Use it only as an example, copy-pasting randomly won't help you. Modify this first to your needs

    Also please don't forget to read the comments in the code .

    The Code

    Use this as a method in your class to check 1st whether the column you want to add is missing . We do this just to not repeat the process of altering the table receipt_barcode. Just mention it as part of your class. In the next step you'll see how we'll use it.

    public boolean is_column_exists(SQLiteDatabase mDatabase , String table_name,
    String     column_name) {
        //checks if table_name has column_name
        Cursor cursor = mDatabase.rawQuery("pragma table_info("+table_name+")",null);
        while (cursor.moveToNext()){
        if (cursor.getString(cursor.getColumnIndex("name")).equalsIgnoreCase(column_name)) return true;
        }
        return false;
    }
    

    Then , the following code is used to create the table receipt_barcode if it already does NOT exit for the 1st time users of your app. And please notice the "IF NOT EXISTS" in the code. It has importance.

    //mDatabase should be defined as a Class member (global variable) 
    //for ease of access : 
    //SQLiteDatabse mDatabase=SQLiteDatabase.openOrCreateDatabase(dbfile_path, null);
    creation_query = " CREATE TABLE if not exists receipt_barcode ( ";
    creation_query += "\n record_id        INTEGER PRIMARY KEY AUTOINCREMENT,";
    creation_query += "\n rcpt_id INT( 11 )       NOT NULL,";
    creation_query += "\n barcode VARCHAR( 255 )  NOT NULL ,";
    creation_query += "\n barcode_price VARCHAR( 255 )  DEFAULT (0),";
    creation_query += "\n PRIMARY KEY ( record_id ) );";
    mDatabase.execSQL(creation_query);
    
    //This is where the important part comes in regarding the question in this page:
    
    //adding the missing primary key record_id in table receipt_barcode for older versions
            if (!is_column_exists(mDatabase, "receipt_barcode","record_id")){
                mDatabase.beginTransaction();
                try{
                    Log.e("record_id", "creating");
    
    
                     creation_query="CREATE TEMPORARY TABLE t1_backup(";
                     creation_query+="record_id INTEGER        PRIMARY KEY AUTOINCREMENT,";
                     creation_query+="rcpt_id INT( 11 )       NOT NULL,";
                     creation_query+="barcode VARCHAR( 255 )  NOT NULL ,";
                     creation_query+="barcode_price VARCHAR( 255 )  NOT NULL DEFAULT (0) );";
                     mDatabase.execSQL(creation_query);
    
                     creation_query="INSERT INTO t1_backup(rcpt_id,barcode,barcode_price) SELECT rcpt_id,barcode,barcode_price  FROM receipt_barcode;";
                     mDatabase.execSQL(creation_query);
    
                     creation_query="DROP TABLE receipt_barcode;";
                     mDatabase.execSQL(creation_query);
    
                     creation_query="CREATE TABLE receipt_barcode (";
                     creation_query+="record_id INTEGER        PRIMARY KEY AUTOINCREMENT,";
                     creation_query+="rcpt_id INT( 11 )       NOT NULL,";
                     creation_query+="barcode VARCHAR( 255 )  NOT NULL ,";
                     creation_query+="barcode_price VARCHAR( 255 )  NOT NULL DEFAULT (0) );";
                     mDatabase.execSQL(creation_query);
    
                     creation_query="INSERT INTO receipt_barcode(record_id,rcpt_id,barcode,barcode_price) SELECT record_id,rcpt_id,barcode,barcode_price  FROM t1_backup;";
                     mDatabase.execSQL(creation_query);
    
                     creation_query="DROP TABLE t1_backup;";
                     mDatabase.execSQL(creation_query);
    
    
                     mdb.setTransactionSuccessful();
                } catch (Exception exception ){
                    Log.e("table receipt_bracode", "Table receipt_barcode did not get a primary key (record_id");
                    exception.printStackTrace();
                } finally {
                     mDatabase.endTransaction();
                }
    

提交回复
热议问题