我正在開發一個項目並且不理解我在線發現的這段代碼的這部分內容。 (我也看過其他的例子,他們做了完全相同的事情,但我不太明白爲什麼)如何將行插入到SQLite表中而不指定主鍵的值
當他們在表中插入某些東西時,他們對主鍵沒有任何價值。有人可以向我解釋爲什麼是這樣嗎?
以下是我發現的兩個代碼示例,按照上面的說明進行操作。 謝謝。
//As you can see a contact has 3 attributes.
int _id;
String _name;
String _phone_number;
// Where they create a table. As you can see the primary key is ID
@Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT, + KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Adding new contact
//*This is what I don't understand. Why don't they get an ID for the contact.
//They only have values for the name and phone number when they insert it into the table.*
public void addContact(Contact contact)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
繼承人另一個例子,但這是使用一本書。 一本書有3個屬性,一個id(主鍵),一個作者和書名。再次,他們沒有得到主鍵的價值。
public void addBook(Book book)
{
Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TITLE, book.getTitle()); // get title
values.put(KEY_AUTHOR, book.getAuthor()); // get author
// 3. insert
db.insert(TABLE_BOOKS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}