尝试在sqlite数据库表中查询所有行时,我收到以下异常:
08-24 20:36:48.134: E/AndroidRuntime(351): java.lang.RuntimeException:
Unable to start activity ComponentInfo{se.p950tes.workouttracker/se.p950tes.workouttracker.SavedActivity}:
android.database.sqlite.SQLiteException: no such column: col_distance: ,
while compiling: SELECT _id, col_date, col_time, col_distance, col_route FROM workout
我还没有更新数据库,这是我第一次在这个设备上安装应用程序,并且它也在模拟器上进行了测试,结果相同。即便如此,我还是尝试了几次版本号,没有任何变化。
这是我的代码。 getAll方法抛出异常。
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler
{
public static final String DATABASE_NAME = "workout_tracker";
private static final String KEY_ID = "_id";
private static final String KEY_DATE = "col_date";
private static final String KEY_TIME = "col_time";
private static final String KEY_DISTANCE = "col_distance";
private static final String KEY_ROUTE = "col_route";
private static final String TABLE = "workout";
private static final String[] ALL_FIELDS = {KEY_ID, KEY_DATE, KEY_TIME, KEY_DISTANCE, KEY_ROUTE};
private static final int DATABASE_VERSION = 3;
private final Context context;
private DatabaseHelper helper;
private SQLiteDatabase db;
public DatabaseHandler(Context context)
{
this.context = context;
this.helper = new DatabaseHelper(context);
}
public void connect()
{
db = helper.getWritableDatabase();
}
public void disconnect()
{
db.close();
}
public Cursor getAll()
{
return db.query(TABLE, ALL_FIELDS, null, null, null, null, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
private static final String CREATE = "CREATE TABLE " + TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_DATE + " INTEGER NOT NULL, "
+ KEY_TIME + " INTEGER NOT NULL, "
+ KEY_DISTANCE + "INTEGER NOT NULL, "
+ KEY_ROUTE + " BLOB NOT NULL"
+ ");";
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try
{
db.execSQL(CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("DBHandler", "Upgrading database from version "+oldVersion+" to "+newVersion+", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS "+TABLE);
onCreate(db);
}
}
}
我意识到这个“我为什么会得到这个SQLiteException”的问题被问了很多,但到目前为止,我见过的大多数问题都没有用引号括起字符串等等。如果结果是重复,我会提前道歉。
答案 0 :(得分:8)
您错过了"INTEGER NOT NULL, "
中的前导空格。