Android插入/更新/删除SQLite查询

时间:2011-09-12 15:39:06

标签: android sqlite

我正在尝试编写三种不同的方法来在Android中的SQLite数据库中插入,更新和删除数据。到目前为止,我可以在数据库中插入数据,但我无法理解如何在SQL中添加where子句。 这是我正在使用的代码:

更新方法:

public boolean updateSQL(String tableName,String key,String value){
    return updateData(tableName,key,value);
}

private static boolean updateData(String tableName,String key,String value){
    sqliteDb = instance.getWritableDatabase();
    String where = "id=?";
    ContentValues values = new ContentValues();
    values.put(key, value);
    values.put(key, value);
    sqliteDb.update(tableName, values, where, null);
    return true;
}

...我正在调用这个方法:

dbHelper.updateSQL("saved_codes", "code_id", "3");
//dbHelper is an instance to a custom DatabaseHelper class.

..和删除方法:

public boolean deleteSQL(String tableName,String key,String value){
    return deleteData(tableName,key,value);
}

private static boolean deleteData(String tableName,String key,String value) {
    sqliteDb = instance.getWritableDatabase();
    ContentValues values = new ContentValues();
    String where = null;
    String[] whereArgs = null;
    values.put(key, value);
    values.put(key, value);
    sqliteDb.delete(tableName, where, whereArgs);
    return true;
}

我知道字符串wherewhereArgsnull,但实际上我无法理解如何添加它们。 我不希望有人为我编写代码,但欢迎来自互联网的一些好的建议,建议甚至样本。

3 个答案:

答案 0 :(得分:5)

你需要whereArgs

String where = "id=?";

类似的东西:

sqliteDb.update(tableName, values, where, new String[] {"42"});

其中42将是要更新的行的_id。也更喜欢BaseColumns._ID到“id”。

答案 1 :(得分:0)

public class Database {

    public static final String DATABASE_NAME="bookdb";

    public static final int DATABASE_VERSION=1;

    public static final String TABLE_NAME="tbbook";

    public static final String ISDN="isdn";

    public static final String TITLE="title";;

    public static final String AUTHOR="author";

    public static final String PRICE="price";

    public static final String TABLE_CREATE="create table tbbook(isdn INT,title TEXT,author TEXT,price FLOAT);";

    Context ctx;
    SQLiteDatabase db;
    DatabaseHelper dbhelper;

    public Database(Context ctx){
        this.ctx=ctx;
        dbhelper=new DatabaseHelper(ctx);
    }

    class DatabaseHelper extends SQLiteOpenHelper{

        public DatabaseHelper(Context ctx) {
            super(ctx,DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub

            db.execSQL(TABLE_CREATE);
            Toast.makeText(Database.this.ctx,"Database is created",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXIST");
            onCreate(db);
        }

    }

    public long insertData(int bisdn,String btitle,String bauthor,float bprice){

        ContentValues intialvalues=new ContentValues();

        intialvalues.put(ISDN, bisdn);
        intialvalues.put(TITLE, btitle);
        intialvalues.put(AUTHOR, bauthor);
        intialvalues.put(PRICE,bprice);

        Log.d("isdn==",bisdn+"");
        Log.d("title==",btitle+"");
        Log.d("author==",bauthor+"");
        Log.d("price==",bprice+"");

        Toast.makeText(ctx,"values inserted",Toast.LENGTH_SHORT).show();




        return db.insert(TABLE_NAME, null,intialvalues);

    }

    public Database open(){

        db=dbhelper.getWritableDatabase();
        return this;

    }
    public void close(){
        dbhelper.close();
    }

    public Cursor getAllData(){

        String query="select * from tbbook";
        Log.d("query==",query);
        Cursor cur=db.rawQuery(query, null);

        return cur;

    }

    public void updateData(String bisdn,String btitle,String bauthor,float bprice){

        ContentValues intialvalues=new ContentValues();


        intialvalues.put(TITLE, btitle);
        intialvalues.put(AUTHOR, bauthor);
        intialvalues.put(PRICE,bprice);


        Log.d("title==",btitle+"");
        Log.d("author==",bauthor+"");
        Log.d("price==",bprice+"");



        db.update(TABLE_NAME,intialvalues,ISDN+" = ? ",new String[]{bisdn});

        Log.d("values","updated");

        Toast.makeText(ctx,"values updated",Toast.LENGTH_SHORT).show();

    }

    public void DeleteData(String bisdn)
    {

        db.delete(TABLE_NAME,ISDN+"=?",new String[]{bisdn});

        Log.d("values","deleted");
        Toast.makeText(ctx,"delete value",Toast.LENGTH_SHORT).show();
    }

    public void DeleteAllData()
    {

        db.delete(TABLE_NAME,null,null);

        Log.d("all","deleted");
        Toast.makeText(ctx,"all record deleted",Toast.LENGTH_SHORT).show();
    }

}

//////如何调用每个方法/////

public void load_custom_view(){

    try {
        detail=new ArrayList<BookPojo>();
        database=new Database(CustomViewActivity.this);
        database.open();
        Cursor c=database.getAllData();
        if(c.moveToFirst())
        {
            do{
                detail.add(new BookPojo(c.getInt(0),c.getString(1), c.getString(2),c.getFloat(3)));

            }while(c.moveToNext());
        }
        c.close();
        database.close();
        messagelist.setAdapter(new CustomAdapter(detail,CustomViewActivity.this));




    } catch (Exception e) {
        // TODO: handle exception
    }

}


btnsubmit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             bisdn=edtisdn.getText().toString();
             btitle=edttitle.getText().toString();
             bauthor=edtauthor.getText().toString();
             bprice=edtprice.getText().toString();

            /*Database databse=new Database(InsertActivity.this);
            databse.open();
            databse.insertData(bisdn,btitle,bauthor,bprice);
            databse.close();*/


        }
});


public void create_dialog() {

    builder = new AlertDialog.Builder(this);
    builder.setTitle("Warning!");
    builder.setMessage("Are you sure to delete isdn="+bisdn);
    builder.setIcon(R.drawable.ic_launcher);
    builder.setCancelable(false);

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

            Database database = new Database(VUDActivity.this);
            database.open();
            database.DeleteData(bisdn);
            database.close();


        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

            Toast.makeText(getApplicationContext(), "Not deleted",
                    Toast.LENGTH_LONG).show();

        }
    });
    builder.show();

}

答案 2 :(得分:-1)

更新

    public boolean updaterow(String name)
    {
     SQLitedatabase db=this.getwriteabledatabase();
     Contentvalue value=new Contentvalue();
     value.put("name","paresh");
     
     long result=db.update(databasename,value,"name="+name,null)
        if(result == -1)
        return false,
        else
       return true;
     }
    
    

对于插入数据

    public boolean insertrow(String name)
    {
     SQLitedatabase db=this.getWriteabledatabase();
     Contentvalue value=new Contentvalue();
     value.put("name",name);
     
     long result=db.insert(databasename,null,value)
        if(result == -1)
        return false,
        else
       return true;
     }
    

用于获取数据

    public Cursor getalldata()
    {
     SQLitedatabase db=this.getWriteabledatabase();
    Cursor res=db.rawQuery("select * from"+databasename,null)
       return true;
 
    

用于删除一行

    public void deleteonerow(int id)
    {
     SQLitedatabase db=this.getWriteabledatabase();
    db.exeSQL(db.rawQuery("DELETE FROM"+databasename+"where id+"="+id);)
    db.close();
 
  
相关问题