为什么我的SQLite无法创建表ID列?

时间:2018-07-12 06:39:00

标签: android mysql database sqlite android-studio

我正在android studio中创建应用,我创建了一个表来存储用户的名称,电子邮件,密码以及用户的 ID 。用户名,电子邮件和密码是通过用户输入传递的,而ID是由计算机自动生成的,当我为这些信息创建表时,上面的3列可以正常工作,但是我无法创建用户的ID列。

这是我创建数据库表的代码:

public class DatabaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME ="contacts.db";
private static final String TABLE_NAME ="contacts";
private static final String COLUMN_ID ="id";
private static final String COLUMN_NAME ="name";
private static final String COLUMN_EMAIL ="email";
private static final String COLUMN_PASS ="pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id INTEGER primary key NOT NULL ," +
        "name text not null, email text not null, pass text not null);";

public DatabaseHelper(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {  // create database
    db.execSQL(TABLE_CREATE);
    this.db = db;
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    String query = "DROP TABLE IF EXISTS " + TABLE_NAME;
    db.execSQL(query);
    this.onCreate(db);
}

public void insertContact(Contact c){
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    String query = "select * from contacts";
    Cursor cursor = db.rawQuery(query, null);

    int count = cursor.getCount();

     values.put(COLUMN_ID, count);
    values.put(COLUMN_NAME, c.getUser_name());
    values.put(COLUMN_EMAIL, c.getUser_email());
    values.put(COLUMN_PASS, c.getUser_password());

    db.insert(TABLE_NAME, null, values); // insert into database
    db.close();
}

public String searchPass(String uname){
    db = this.getReadableDatabase();
    String query = "select uname, pass from " + TABLE_NAME;
    Cursor cursor = db.rawQuery(query, null);
    String a, b;
    b = "not found";

    if (cursor.moveToFirst()){
        do {
            a = cursor.getString(0);

            if (a.equals(uname)){
                b = cursor.getString(1);
                break;
            }
        }while (cursor.moveToNext());
    }
    return b;
}

在测试我的应用程序时,我将其粘贴到“名称= abc,电子邮件= abc,密码= abc”中,它显示以下问题:

  

07-12 15:26:27.621 7943-7943 / com.example.haoch.myapplication   E / SQLiteLog:(1)       表联系人没有名为id的列       07-12 15:26:27.625 7943-7943 / com.example.haoch.myapplication       E / SQLiteDatabase:插入电子邮件= abc名称= abc密码= abc id = 0时出错       android.database.sqlite.SQLiteException:表联系人没有名为       id(代码1):,编译时:INSERT INTO联系人(电子邮件,姓名,通行证,ID)       值(?,?,?,?)

1 个答案:

答案 0 :(得分:0)

您是否更改了数据库结构? 在这种情况下,每次更改数据库结构时,都必须增加数据库版本:

private static final int DATABASE_VERSION = 2;

或者,您可以在设备上重新安装该应用或清除该应用的数据