简体   繁体   English

如何更新sqlite记录?

[英]How to update sqlite record?

I coded this for my school project. 我为我的学校项目编写了代码。 It crashes when I call update method. 当我调用更新方法时会崩溃。 error is given below : 错误如下:

E/SQLiteLog: (1) table userInfo has no column named userInfo E/SqDb: Err ins ... android.database.sqlite.SQLiteException: table userInfo has no column named userInfo (code 1): , while compiling: INSERT INTO userInfo(password,userInfo) VALUES (?,?) at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:921) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:532) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58) at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31) at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1570) at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1427) at com.example.prabuddhaabisheka.mock.DBHelper.addInfo(DBHelper.java:46) at com.example.prabuddhaabisheka.mock.Home$2.onClic E / SQLiteLog:(1)表userInfo没有名为userInfo的列E / SqDb:错误... android.database.sqlite.SQLiteException:表userInfo没有名为userInfo的列(代码1):,而正在编译:INSERT INTO userInfo (password,userInfo)在android.database.sqlite.SQLiteConnection.nativePrepareStatement(本地方法)处的值(?,?)在android.database.sqlite.SQLiteConnection处的android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:921)处的值在android.database.sqlite.SQLite.SQLiteSession.prepare(SQLiteSession.java:588)在android.database.sqlite.SQLiteProgram。(SQLiteProgram.java:58)的.prepare(SQLiteSession.java:588)在android.database.sqlite.SQLiteStatement的。(SQLiteStatement.java:31)在android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1570)在android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1427)在com.example.prabuddhaabisheka.mock com.example.prabuddhaabisheka.mock.Home $ .onClic上的.DBHelper.addInfo(DBHelper.java:46) k(Home.java:59) at android.view.View.performClick(View.java:5232) at android.view.View$PerformClick.run(View.java:21289) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:168) at android.app.ActivityThread.main(ActivityThread.java:5885) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) android.view.View.performClick(View.java:5232)的k(Home.java:59)android.os.Handler.handleCallback(Handler)处的android.view.View $ PerformClick.run(View.java:21289)处.java:739),位于android.os.Handler.dispatchMessage(Handler.java:95),位于android.os.Looper.loop(Looper.java:168),位于android.app.ActivityThread.main(ActivityThread.java:5885)在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:797)的com.android.internal.os.ZygoteInit.main(ZygoteInit)的java.lang.reflect.Method.invoke(本机方法)处。 Java的:687)

public class EditProfile extends AppCompatActivity {

Button search, edit, delete;
EditText name, password, dob;
RadioButton male,female;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_profile);

    search = findViewById(R.id.buttonSerach);
    edit = findViewById(R.id.buttonEdit);
    delete = findViewById(R.id.Delete);

    name = findViewById(R.id.editTextName);
    password = findViewById(R.id.editTextPassword);
    dob = findViewById(R.id.editTextDOB);
    male = (RadioButton) findViewById(R.id.radioButtonMale);
    female = findViewById(R.id.radioButtonFemale);

}

public void  search(View view){

    DBHelper dbHelper = new DBHelper(this);

    String givenName = name.getText().toString();

    ArrayList<userInfo> user ;

    user = dbHelper.readAllInfo();

    if(!user.isEmpty()) {
        for (userInfo u : user) {

            if (givenName.equals(u.name)) {

                password.setText(u.password);
                dob.setText(u.dob);
                if ("Male".equals(u.gender)) {
                    male.setChecked(true);
                    female.setChecked(false);
                } else {

                    male.setChecked(false);
                    female.setChecked(true);
                }
            }
        }
    }
}

public void update(View view){

    DBHelper dbHelper = new DBHelper(this);

    String givenName = name.getText().toString();

    int id = 0;

    ArrayList<userInfo> user;

    user = dbHelper.readAllInfo();

    if(!user.isEmpty()) {

        for (userInfo u : user) {

            if (givenName.equals(u.name)) {

                id = u.id;
            }
        }
    }
    String givenDob = dob.getText().toString();
    String givenPassword = name.getText().toString();

    String gender;

    if (male.isChecked()){

        gender = "Male";
    }
    else{
        gender = "Female";
    }


    boolean updated = dbHelper.updateInfo(id,givenName,givenPassword,givenDob,gender);

    if (updated) {
        Toast toast = Toast.makeText(this, "Updated", Toast.LENGTH_SHORT);
        toast.show();
    }
    else{
        Toast toast = Toast.makeText(this, "Update failed !", Toast.LENGTH_SHORT);
        toast.show();
    }

}


}

DBHelper class is also given below 下面也给出了DBHelper类

 public class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context) {
    super(context, UserProfile.Users.DB_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    String createTable = "CREATE TABLE "+ UserProfile.Users.TABLE_NAME +" ("+
            UserProfile.Users._ID + "INTEGER PRIMARY KEY," +
            UserProfile.Users.TABLE_COLUMN_USERNAME + "TEXT,"+
            UserProfile.Users.TABLE_COLUMN_PASSWORD + "TEXT," +
            UserProfile.Users.TABLE_COLUMN_DOB + "TEXT,"+
            UserProfile.Users.TABLE_COLUMN_GENDER + "TEXT)";

    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public boolean addInfo( ContentValues values ){

    SQLiteDatabase db = getWritableDatabase();

    long added = db.insert(UserProfile.Users.TABLE_NAME,null,value);

    return (added != 0);
}

public boolean updateInfo(int id, String name, String password, String dob, String gender ){

    SQLiteDatabase db = getReadableDatabase();

    ContentValues values = new ContentValues();

    values.put(UserProfile.Users.TABLE_COLUMN_USERNAME,name);
    values.put(UserProfile.Users.TABLE_COLUMN_PASSWORD,password);
    values.put(UserProfile.Users.TABLE_COLUMN_DOB,dob);
    values.put(UserProfile.Users.TABLE_COLUMN_GENDER,gender);

    String where = UserProfile.Users._ID + " =";

    String[] arg = {Integer.toString(id)};

    int row = db.update(UserProfile.Users.TABLE_NAME, values, where, arg);

    return (row !=0 );
}

public ArrayList readAllInfo(){

    SQLiteDatabase db = getReadableDatabase();

    String[] columns = {
            UserProfile.Users._ID,
            UserProfile.Users.TABLE_COLUMN_USERNAME,
            UserProfile.Users.TABLE_COLUMN_PASSWORD,
            UserProfile.Users.TABLE_COLUMN_GENDER,
            UserProfile.Users.TABLE_COLUMN_DOB
    };

    Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,columns,null,null,null
    ,null,null);

    ArrayList<userInfo> users = new ArrayList<>();

    while (cursor.moveToNext()){

        int id = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_USERNAME));
        String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_DOB));
        String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_GENDER));
        String password = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_PASSWORD));

        userInfo user = new userInfo(id,name,password,dob,gender);

        users.add(user);
    }

    cursor.close();
    return users;
}

public ArrayList readAllInfo(int id){

    SQLiteDatabase db = getReadableDatabase();

    String[] columns = {
            UserProfile.Users._ID,
            UserProfile.Users.TABLE_COLUMN_USERNAME,
            UserProfile.Users.TABLE_COLUMN_PASSWORD,
            UserProfile.Users.TABLE_COLUMN_GENDER,
            UserProfile.Users.TABLE_COLUMN_DOB
    };

    String where = UserProfile.Users._ID + " =?";
    String[] arg = {Integer.toString(id)};

    Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,columns,where,arg,null
    ,null,null);

    ArrayList<userInfo> users = new ArrayList<>();

    while (cursor.moveToNext()){

        //int ID = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_USERNAME));
        String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_DOB));
        String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_GENDER));
        String password = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_PASSWORD));

        userInfo user = new userInfo(id,name,password,dob,gender);

        users.add(user);
    }

    cursor.close();
    return users;
}

public void deleteUser(int ID){

    SQLiteDatabase db = getReadableDatabase();

    String where = UserProfile.Users._ID + " =?";
    String[] arg = {Integer.toString(ID)};

    int count = db.delete(UserProfile.Users.TABLE_NAME,where,arg);

}

} }

The error is clear: 错误很明显:

...
.sqlite.SQLiteException: table userInfo has no column named userInfo (code 1):
, while compiling: INSERT INTO userInfo(password,userInfo) VALUES (?,?) at
...

When you are invoking the method 调用方法时

public boolean addInfo( ContentValues values )

You are passing as a content value, a value named with the same name as the table. 您正在传递的内容值是与表同名的值。 You have to check two things: 您必须检查两件事:

  1. Where you are using UserProfile.Users.TABLE_NAME (that I suppose it has the value userInfo 您在哪里使用UserProfile.Users.TABLE_NAME (我想它的值是userInfo
  2. Check what you are passing to content values used by addInfo method. 检查您要传递给addInfo方法使用的内容值的内容。

Hope it helps. 希望能帮助到你。

If you are trying to add new row to the table after it has been created, try to remove the table and create it again. 如果要在创建新行后将其添加到表中,请尝试删除该表并重新创建。

to remove 去除

 sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

after this, you can recreate the table again 之后,您可以重新创建表

You have to increase your version of database after then do changes in On-upgrade method of sqlite. 在更改sqlite的On-upgrade方法之后,您必须增加数据库的版本。

   @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        if(newVersion > oldVersion){
            db.execSQL("DROP TABLE IF EXISTS " +......);
            db.execSQL("CREATE TABLE IF NOT EXISTS " +......);

            insertColumnIfNotAvailableinTable(SQLiteDatabase db, String tableName, String columnName, String columnType);



        }
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM