table用户没有名为USERNAME(代码1)的列:,同时编译:INSERT INTO用户(USERNAME,PASSWORD)VALUES(?,?)

时间:2017-11-15 17:59:05

标签: android sqlite android-studio

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);
    }
}

1 个答案:

答案 0 :(得分:2)

您的代码存在多个问题。

首先,您的onCreate()onUpgrade()没有被执行。数据库文件已经是版本1.您可以卸载应用程序以删除其旧数据库文件。 When is SQLiteOpenHelper onCreate() / onUpgrade() run?

然后会触发NullPointerException,因为db未初始化。 onCreate()onUpgrade()需要使用传入的SQLiteDatabase作为方法的参数,而不是尚未初始化的字段。