我正在开发一个项目并且不理解我在线发现的这段代码的这部分内容。 (我也看过其他的例子,他们做了完全相同的事情,但我不太明白为什么)如何将行插入到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();
}