logcat的
错误插入USERNAME = raj PASSWORD = raj android.database.sqlite.SQLiteException:table用户没有名为USERNAME(代码1)的列:,编译时:INSERT INTO 用户(USERNAME,PASSWORD)VALUES(?,?)
代码
package com.example.aaru.sqlapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydatabase.db";
public static final String TABLE = "User";
public static final String UNAME = "USERNAME";
public static final String PASS = "PASSWORD";
public static final String ID = "UID";
SQLiteDatabase db=this.getWritableDatabase();
public DBHelper(Context context) {
super(context, DBNAME, null, 1);
//create database when we create DBHelper object
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//create table
db.execSQL("create table "+TABLE+"(" + ID + " integer primary key autoincrement," + UNAME + " text," + PASS + " text)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//Delete table if table is already exists
db.execSQL("DROP TABLE IF EXISTS User");
onCreate(sqLiteDatabase);
}
public long insert(String uname, String pass){
ContentValues values = new ContentValues();
values.put(UNAME, uname);
values.put(PASS, pass);
return db.insert(TABLE, null, values);
}
}
答案 0 :(得分:2)
您的代码存在多个问题。
首先,您的onCreate()
和onUpgrade()
没有被执行。数据库文件已经是版本1.您可以卸载应用程序以删除其旧数据库文件。 When is SQLiteOpenHelper onCreate() / onUpgrade() run?
然后会触发NullPointerException
,因为db
未初始化。 onCreate()
和onUpgrade()
需要使用传入的SQLiteDatabase
作为方法的参数,而不是尚未初始化的字段。