我使用SQLite创建了一个数据库,我似乎正确地创建了数据库,空间和所有,但是当我运行应用程序时,我得到的异常是它找不到列id:“_ id”
请查看我的代码,让我知道我做错了什么。
public static final String KEY_ROW_ID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String RATE = "rate_it";
private static final String DATABASE_NAME = "iDRateIt";
private static final String DATABASE_TABLE = "tblPeople";
private static final int DATABASE_VERSION = 1;
private dbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class dbHelper extends SQLiteOpenHelper {
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ( " +
KEY_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
RATE + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//Constructor
public RateIt (Context c) {
ourContext = c;
}
public RateIt open() throws SQLException
{
ourHelper = new dbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
//Close Database
public void close()
{
ourHelper.close();
}
//Insert Method
public long createEntry(String name, String rate) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(RATE, rate);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROW_ID, KEY_NAME, RATE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROW_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iRate = c.getColumnIndex(RATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iRate) + "\n";
}
return result;
}
}
答案 0 :(得分:0)
你确定它正确创造吗?因为
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ( " +
KEY_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
RATE + " TEXT NOT NULL);"
似乎有一个分散的分号,应该是:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ( " +
KEY_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
RATE + " TEXT NOT NULL)"
答案 1 :(得分:0)
看起来
存在问题c.getString(iRow)
从代码中将_id列定义为整数
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ( " +
KEY_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
您需要将此视为整数
int iRow =(c.getLong(c.getColumnIndex(KEY_ROW_ID))); 或
int iRow = (c.getInteger(c.getColumnIndex(KEY_ROW_ID)));
希望这有帮助。
此外,您已定义费率
RATE + " TEXT NOT NULL
作为文本字段,如果你这样做只是为了测试目的,但良好的数据库设计会将其定义为某种类型的数字字段,即Integer,Long。
度过美好的一天。