gamesdatabase = openOrCreateDatabase("GamesDatabase", MODE_PRIVATE, null);
gamesdatabase.execSQL("CREATE TABLE IF NOT EXISTS Games (ID INTEGER PRIMARY KEY, Name
VARACHAR, NPlayers INT(1), NRounds INT(2), WinScore INT(2));");
gamesdatabase.execSQL("INSERT INTO Games
(ID, Name, NPlayers, NRounds, WinScore ) VALUES ( NULL, 'TAWLA',2,0,0 );");
gamesdatabase.execSQL("INSERT INTO Games
(ID, Name, NPlayers, NRounds, WinScore ) VALUES ( NULL, 'DOMANA',4,0,0 );");
Cursor c = gamesdatabase.rawQuery("SELECT * FROM Games", null);
c.moveToFirst();
while (c.isAfterLast() == false) {
Log.d("BEZRA", String.valueOf(c.getInt(c.getColumnIndex("ID"))));
c.moveToNext();
}
这有什么问题?所有记录的日志显示为0
答案 0 :(得分:28)
SQLite表的主键称为_id。它是自动递增的,您不应该尝试在其中插入值。
gamesdatabase = openOrCreateDatabase("GamesDatabase", MODE_PRIVATE, null);
gamesdatabase.execSQL("CREATE TABLE IF NOT EXISTS Games (_id INTEGER PRIMARY KEY, Name
VARACHAR, NPlayers INT(1), NRounds INT(2), WinScore INT(2));");
gamesdatabase.execSQL("INSERT INTO Games
(Name, NPlayers, NRounds, WinScore ) VALUES ('TAWLA',2,0,0 );");
gamesdatabase.execSQL("INSERT INTO Games
(Name, NPlayers, NRounds, WinScore ) VALUES ('DOMANA',4,0,0 );");
Cursor c = gamesdatabase.rawQuery("SELECT * FROM Games", null);
c.moveToFirst();
while (c.isAfterLast() == false) {
Log.d("BEZRA", String.valueOf(c.getInt(c.getColumnIndex("_id"))));
c.moveToNext();
}
答案 1 :(得分:6)
对我有用的是将我的创建类型从INT重命名为INTEGER并开始工作。
由此:
CREATE TABLE IF NOT EXISTS foo (id INT PRIMARY KEY, bar INT)
到此:
CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, bar INT)
答案 2 :(得分:2)
c.getColumnIndex("ID")
获取列的索引,其中ID为0索引列,名称为1等
你想要
c.getInt(c.getColumnIndex("ID"))
答案 3 :(得分:1)
你可以看到 http://alvinalexander.com/android/sqlite-autoincrement-serial-identity-primary-key 示例强> CRETAE_TABLE
CREATE TABLE salespeople (
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
commission_rate REAL NOT NULL
);
INSERT_DATA
INSERT INTO salespeople VALUES (null, 'Fred', 'Flinstone', 10.0);
--- --- OR
INSERT INTO salespeople (first_name, last_name, commission_rate) VALUES ('Fred', 'Flinstone', 10.0);
答案 4 :(得分:0)
您想告诉它该列是自动递增的。
ID INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL
代替。
答案 5 :(得分:-1)
因为您没有将其设置为自动增量。主键是不够的。
CREATE TABLE IF NOT EXISTS Games (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name VARACHAR, NPlayers INT(1), NRounds INT(2), WinScore INT(2));