10

好的,这不是垃圾邮件,应该很简单我不知道为什么它不起作用这是我的代码:

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

4

6 回答 6

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();
}
于 2013-05-30T09:30:10.287 回答
11

对我有用的是将我的创建类型从 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)
于 2016-06-02T23:38:16.097 回答
2

c.getColumnIndex("ID") 获取列的索引,其中 ID 为 0 索引列,名称为 1 等

你要

c.getInt(c.getColumnIndex("ID"))

于 2013-05-30T09:30:13.663 回答
2

您可以看到 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 INTO salespeople VALUES (null, 'Fred', 'Flinstone', 10.0);

- -或者 - -

INSERT INTO salespeople (first_name, last_name, commission_rate) VALUES ('Fred', 'Flinstone', 10.0);
于 2015-10-12T05:07:07.817 回答
0

您想告诉它该列是自动递增的。

ID INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL

反而。

于 2013-05-30T09:27:30.337 回答
-1

因为您没有将其设置为自动递增。主键是不够的。

CREATE TABLE IF NOT EXISTS Games (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name VARACHAR, NPlayers INT(1), NRounds INT(2), WinScore INT(2));
于 2013-05-30T09:26:54.773 回答