简体   繁体   English

如何在SQLite中更新特定行?

[英]How to update a specific row in SQLite?

Im trying to update a users current credits, but I don't want to replace the value, just add on a selected amount from the spinner and add it on to the the users current credits? 我正在尝试更新用户的当前信用,但我不想替换该值,只需从微调器中添加选定的金额,然后将其添加到用户的当前信用? Thank you. 谢谢。

My database code? 我的数据库代码?

package com.example.parkangel;

public class UDbHelper extends SQLiteOpenHelper
{
    public static final String KEY_ROWID = "_id";
    public static final String KEY_PFNAME = "payeeFname";
    public static final String KEY_PSNAME = "payeeSname";
    public static final String KEY_CARD = "card";
    public static final String KEY_CREDITS = "credits";

    private static final String DATABASE_NAME = "UserData.db";
    private static final String DATABASE_TABLE = "UserTable";
    private static final int DATABASE_VERSION = 1;

    //private UDbHelper dbHelper;
    //private final Context ourContext;
    private static UDbHelper instance;
    private SQLiteDatabase ourDatabase;

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

    public static UDbHelper getInstance(Context context)
    {
        if (instance == null)
        {
            instance = new UDbHelper(context);  
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + " 
                                    TEXT NOT NULL, " +
                KEY_CARD + " INTEGER NOT NULL, " + KEY_CREDITS + " 
                                    INTEGER NOT NULL);");   

        ContentValues values = new ContentValues();
        values.put(KEY_PFNAME, "Tutku"); 
        values.put(KEY_PSNAME, "Erbil");
        values.put(KEY_CARD, "12345677"); 
        values.put(KEY_CREDITS, 5);
        db.insert(DATABASE_TABLE, null, values);
    }

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

        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }

    public synchronized UDbHelper open() throws SQLException
    {
        System.out.println ("running open");
        if(ourDatabase == null || !ourDatabase.isOpen())
        ourDatabase = getWritableDatabase();
        return this;
    }   

    public String getData() 
    {
        // TODO Auto-generated method stub
        String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
            KEY_CARD, KEY_CREDITS};
        Cursor  c = ourDatabase.query(DATABASE_TABLE, columns, null, null, 
                                                 null, null, null);
        String result = " ";

        int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
        int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
        int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
        int iCard = c.getColumnIndexOrThrow(KEY_CARD);
        int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);

        for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + c.getString(iRow) + " " + 
                            c.getString(iPFname) + " " +
            c.getString(iPSname) + " " + c.getString(iCard) + " " +
            c.getString(iCredits) + "\n";
        }
        return result;
    }

    public void upDateUser(String money) {
        // TODO Auto-generated method stub
        ContentValues cvUpdate = new ContentValues();
        cvUpdate.put(KEY_CREDITS, money);
        ourDatabase.update(DATABASE_TABLE, cvUpdate, null, null);
    }
}

Class that needs to perform the actoin: 需要执行actoin的类:

package com.example.parkangel;  

public class Balance extends Activity implements OnClickListener{

Button add;
TextView display;
Spinner spinner3;
Integer[] money = new Integer[] {1, 2, 5, 10};  

protected void onCreate(Bundle savedInstanceState) {                
    super.onCreate(savedInstanceState);
    setContentView(R.layout.balance_layout);
    TextView tv = (TextView) findViewById(R.id.firstn);
    UDbHelper db = new UDbHelper(this);
    db.open();
    String data = db.getData();
    //db.addUser();
    db.close();
    tv.setText(data);

    ArrayAdapter<Integer> adapter3 = new ArrayAdapter<Integer>(Balance.this,   
                                     android.R.layout.simple_spinner_item, money);

    spinner3 = (Spinner) findViewById (R.id.moneytoadd);
    spinner3.setAdapter(adapter3);

    add = (Button) findViewById(R.id.topup);
    add.setOnClickListener(this);
    //add = (Button) findViewById(R.id.topup);      
}

public void onClick(View arg0)
{
    switch (arg0.getId()){
    case R.id.topup:

        boolean work = true;
        try{
        String money = spinner3.getContext().toString();

        UDbHelper ud = new UDbHelper(this);
        ud.open();
        ud.upDateUser(money);
        ud.close();

    }catch (Exception e){
        work = false;
        String error = e.toString();
        Dialog d = new Dialog(this);
        d.setTitle("Unable To TopUp!");
        TextView dg = new TextView(this);
        dg.setText(error);
        d.setContentView(dg);
        d.show();
}finally{
    if(work){
        Dialog d = new Dialog(this);
        d.setTitle("You Have ToppedUp!");
        TextView dg = new TextView(this);
        dg.setText("TopUp Successful");
        d.setContentView(dg);
        d.show();
            }
        }   
        break;
}
}

public void updateActivity(View view){
    Intent book = new Intent(Balance.this, BookTicket.class);
    startActivity(book);
}

public void addBalance(View view){
    Intent addB = new Intent(Balance.this, Balance.class);
    startActivity(addB);
}

public void doUpdate(View view){
    Intent upd = new Intent(Balance.this, UpdateTicket.class);
    startActivity(upd);
}

} }

First of all you should have an ID that will let you find the user you are interested in. That do a select to get the current value that is stored in database. 首先,您应该具有一个ID,该ID可让您找到您感兴趣的用户。进行选择以获取存储在数据库中的当前值。 Parse the value to integer and add "new" money. 将值解析为整数,然后添加“新”货币。 And finally, update the value in database. 最后,更新数据库中的值。

public void upDateUser(String ID, String money) {
        String query = "Select money from TABLE_NAME where ID = " + ID;
        SQLiteDatabase db = this.getWriteableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        int oldMoney = 0;
        if (cursor.moveToFirst()) {         
            oldMoney = Integer.parseInt(cursor.getString(0)); //Cause we get only from money column
        }
        ContentValues cvUpdate = new ContentValues();
        cvUpdate.put(KEY_CREDITS, oldMoney  + money);
        String filter = "UID" + "=" + ID;
        db.update(DATABASE_TABLE, cvUpdate, filter, null);
    }

Of course you have to check if cursor returns exactly one row and do some other checks. 当然,您必须检查游标是否正好返回一行,并进行其他一些检查。

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

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