android.database.sqlite.SQLiteException:表用户没有名为friends的列

时间:2016-12-23 02:21:09

标签: android database sqlite

当我尝试在SQLite中插入新行时,我收到错误。我在我的代码中搜索了任何错误,但我找不到任何错误。任何帮助都会很棒!

这是我的错误:

android.database.sqlite.SQLiteException: table user has no column named friends (code 1): , while compiling: INSERT INTO user(email,name,api_key,friends,register_date) VALUES (?,?,?,?,?)

这是我的数据库:

private static final String TABLE_USER = "user";
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_API_KEY = "api_key";
private static final String COLUMN_FRIENDS = "friends";
private static final String COLUMN_REGISTER_DATE = "register_date";

public void onCreate(SQLiteDatabase db) {
    String SQL_CREATE_LOGIN = String.format(
            "CREATE TABLE %s (%s, %s, %s, %s)",
            TABLE_USER,
            String.format("%s integer primary key autoincrement", COLUMN_ID),
            String.format("%s varchar(30)", COLUMN_NAME),
            String.format("%s varchar(40)", COLUMN_EMAIL),
            String.format("%s varchar(32)", COLUMN_API_KEY),
            String.format("%s integer", COLUMN_FRIENDS),
            String.format("%s text", COLUMN_REGISTER_DATE)
    );
    db.execSQL(SQL_CREATE_LOGIN);
);

这是我的插入代码:

public void addUser(String name, String email, String api_key, int friends, String register_date) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, name); // Name
    values.put(COLUMN_EMAIL, email); // Email
    values.put(COLUMN_API_KEY, api_key); // Email
    values.put(COLUMN_FRIENDS, friends); // Friends
    values.put(COLUMN_REGISTER_DATE, register_date); // Created At

    // Inserting Row
    long id = db.insert(TABLE_USER, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "New user inserted into sqlite: " + id);
}

1 个答案:

答案 0 :(得分:1)

试试这个:

public void onCreate(SQLiteDatabase db) {
    String SQL_CREATE_LOGIN = String.format(
            "CREATE TABLE %s (%s, %s, %s, %s, %s, %s)",
            TABLE_USER,
            String.format("%s integer primary key autoincrement", COLUMN_ID),
            String.format("%s varchar(30)", COLUMN_NAME),
            String.format("%s varchar(40)", COLUMN_EMAIL),
            String.format("%s varchar(32)", COLUMN_API_KEY),
            String.format("%s integer", COLUMN_FRIENDS),
            String.format("%s text", COLUMN_REGISTER_DATE)
    );
    db.execSQL(SQL_CREATE_LOGIN);
);

也许您忘了将CREATE TABLE %s (%s, %s, %s, %s)修改为CREATE TABLE %s (%s, %s, %s, %s, %s, %s)。您要创建的表有6列。