我在使用Android的SQLite数据库时遇到了困难,每当我的应用程序尝试与数据库交互时,它就会崩溃。任何帮助将不胜感激。
这是构造函数,onCreate()和onUpgrade()方法:
public DatabaseHelper(Context context){
super(context, dbName, null, dbVersion);
}
public void onCreate(SQLiteDatabase db) {
//SQL to create the rTable
db.execSQL("CREATE TABLE " + rTable +
"(" + colID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
colValue + " Integer, " + colDate + " Date, " + colNotes + "TEXT, ");
//SQL to create the limit table
db.execSQL("CREATE TABLE " + lTable +
"(" + colLimitID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
colLimitUpper + " Integer, " + colLimitLower + " Integer, " +
colLimitDate + " Date, ");
//Create view containing all results
db.execSQL("CREATE VIEW " + viewR +
" AS SELECT " + rTable + "." + colID + " AS _id," +
" " + rTable + "." + colValue + "," +
" " + rTable + "." + colDate + "," +
" " + rTable + "." + colNotes + "," +
" FROM " + rTable
);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Used to upgrade the database if the schema needs to be changed
db.execSQL("DROP TABLE IF EXISTS " + rTable);
db.execSQL("DROP TABLE IF EXISTS " + lTable);
db.execSQL("DROP VIEW IF EXISTS " + viewR);
onCreate(db);
}
这是我用来更新表中行的示例方法:
public int UpdateRows(Object obj) {
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colValue, obj.getValue());
cv.put(colNotes, obj.getNotes());
return db.update(rTable, cv, colID+"=?",
new String []{String.valueOf(obj.get_id())});
}
以下是我用来查看所有行的方法:
public List<Object> getAll() {
SQLiteDatabase db=this.getReadableDatabase();
List<Object> List= new ArrayList<>();
String query = "SELECT * from " +tTable;
Cursor c = db.rawQuery(query, null);
if(c!=null){
c.moveToFirst();
while(c.isAfterLast()){
//Create object
Object obj = new Object("1", "100", "", "");
//Set result values equal to that of result in this row
obj.set_id(c.getString(c.getColumnIndex(colID)));
obj.setDate(c.getString(c.getColumnIndex(colDate)));
obj.setValue(c.getString(c.getColumnIndex(colValue)));
obj.setNotes(c.getString(c.getColumnIndex(colNotes)));
//Add object to list
List.add(obj);
//Move cursor to next row
c.moveToNext();
}
//Close cursor
c.close();
}
//Return list
return List;
}
答案 0 :(得分:1)
SQL命令的语法错误。删除字符串运算符和字符串分隔符后,它们看起来像这样:
CREATE TABLE resultTable
(colID INTEGER PRIMARY KEY AUTOINCREMENT,
colValue Integer, colDate Date, colNotesTEXT,
CREATE TABLE limitTable
(colLimitID INTEGER PRIMARY KEY AUTOINCREMENT,
colLimitUpper Integer, colLimitLower Integer, colLimitDate Date,
CREATE VIEW viewResults
AS SELECT resultTable.colID AS _id,
resultTable.colValue,
resultTable.colDate,
resultTable.colNotes,
FROM resultTable
CREATE TABLE命令以逗号结尾,缺少右括号。用右括号替换最后一个逗号。请注意,代码中的右括号是程序代码的一部分,而不是在sql命令字符串中。还有colNotes
和&#34; TEXT&#34;之间的空格。不见了。
CREATE VIEW在FROM之前有一个逗号。删除这个逗号。
使用formatter会使代码更具可读性并且不易出错。
string cmd = format(
"CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s Integer, %s Date, %s TEXT)",
resultTable, colID, colValue, colDate, colNotes);
db.execSQL(cmd);