zoukankan      html  css  js  c++  java
  • Android-Sqlite-OOP方式操作增删改查

    之前写的数据库增删改查,是使用SQL语句来实现的,Google 就为Android开发人员考虑,就算不会SQL语句也能实现增删改查,所以就有了OOP面向对象的增删改查方式

    其实这种OOP面向对象的增删改查方式,最后系统会自动拼接成SQL语句,然后交给Sqlite.c执行,当然这种OOP面向对象的增删改查有点是,很难写错

    数据库帮助类:

    package liudeli.datastorage.db;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    
        public static MySQLiteOpenHelper mySQLiteOpenHelper;
    
        /**
         * 由于表名每次使用很频繁,所有定义成常量
         */
        public static final String TABLE_NAME = "student_table";
    
        private static final String DB_NAME = "person_info.db";
        private static final int VERSION = 2;
    
        public synchronized static MySQLiteOpenHelper getInstance(Context context) {
            if (null == mySQLiteOpenHelper) {
                mySQLiteOpenHelper = new MySQLiteOpenHelper(context, DB_NAME, null, VERSION);
            }
            return mySQLiteOpenHelper;
        }
    
        /**
         * 当开发者调用 getReadableDatabase(); 或者 getWritableDatabase();
         * 就会通过此构造方法配置的信息 来创建 person_info.db 数据库
         * 此方法的另外作用是,如果存着数据库就打开数据库,不存着数据库就创建数据库
         * @param context 上下文
         * @param name    数据库名
         * @param factory 游标工厂
         * @param version 版本,最低为1
         */
        private MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
    
        /**
         * 此方法是何时调用? ,是需要开发者调用 getReadableDatabase(); 或者 getWritableDatabase();
         * 此方法的作用是,如果没有表就创建打开,如果有表就打开
         * @param db 可执行SQL语句
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table "+TABLE_NAME+"(_id integer primary key autoincrement, name text, age integer);");
        }
    
        /**
         * 此方法用于数据库升级
         * @param db 可执行SQL语句
         * @param oldVersion 以前旧版本的版本号
         * @param newVersion 现在目前最新的版本号
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("alter table "+TABLE_NAME+" add sex text null");
        }
    }

    MainActivity OOP面向对象方式操作 增删改查:

    package liudeli.datastorage;
    
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    import liudeli.datastorage.db.MySQLiteOpenHelper;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private final String TAG = MainActivity.class.getSimpleName();
    
        private MySQLiteOpenHelper mySQLiteOpenHelper;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            mySQLiteOpenHelper = MySQLiteOpenHelper.getInstance(this);
    
            // person_info.db创建成功  table表创建成功  还有一个很重要的作用:刷新数据库 刷新表数据等
            mySQLiteOpenHelper.getReadableDatabase();
            mySQLiteOpenHelper.getWritableDatabase();
    
            initViewListener();
        }
    
        private void initViewListener() {
            Button btQuery = findViewById(R.id.bt_query);
            Button btInsert = findViewById(R.id.bt_insert);
            Button btUpdate = findViewById(R.id.bt_update);
            Button btDelete = findViewById(R.id.bt_delete);
    
            btQuery.setOnClickListener(this);
            btInsert.setOnClickListener(this);
            btUpdate.setOnClickListener(this);
            btDelete.setOnClickListener(this);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
    
        }
    
        /**
         * 虽然之需要一次 getWritableDatabase getReadableDatabase 就可以来,为什么还需要每次点击都执行一次?
         * 答:getWritableDatabase getReadableDatabase 还有一个很重要的作用:刷新数据库 刷新表数据等
         * @param v
         */
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_query: {
                    SQLiteDatabase db = mySQLiteOpenHelper.getReadableDatabase();
                    // SQL语句的方式
                    // Cursor cursor = db.rawQuery("select * from "+MySQLiteOpenHelper.TABLE_NAME+";", null);
    
                    // OOP面向对象的方式 带条件查询
                    /*Cursor cursor = db.query(MySQLiteOpenHelper.TABLE_NAME,
                                            new String[]{"_id", "name", "age"},
                                            "_id = ?",
                                            new String[]{"10"},
                                            null,
                                            null,
                                            "_id desc");*/
    
                    // OOP面向对象的方式 全部查询
                    Cursor cursor = db.query(MySQLiteOpenHelper.TABLE_NAME,
                                    new String[]{"*"},
                                    null,
                                    null,
                                    null,
                                    null,
                                    null);
    
                    while (cursor.moveToNext()) {
                        int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        int age = cursor.getInt(cursor.getColumnIndex("age"));
                        Log.d(TAG, "_id:" + _id + " name:" + name + " age:" + age);
                    }
                    db.close();
                    break;
                }
                case R.id.bt_insert: {
                    SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();
                    // SQL语句的方式
                    db.execSQL("insert into " + MySQLiteOpenHelper.TABLE_NAME + "(name,age) values('刘德利',19);");
    
                    // OOP面向对象的方式
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("name", "张三");
                    contentValues.put("age", 19);
                    long result = db.insert(MySQLiteOpenHelper.TABLE_NAME, null, contentValues);
                    // 受影响行数大于0就是成功了
                    if (result > 0) {
                        alterUser("新增成功");
                    }
                    db.close();
                    break;
                }
                case R.id.bt_update: {
                    SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();
                    // SQL语句的方式
                    // db.execSQL("update student_table set name='德利' where _id = 1;");
    
                    // OOP面向对象的方式
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("name", "张三四五");
                    contentValues.put("age", 100);
                    int result = db.update(MySQLiteOpenHelper.TABLE_NAME, contentValues, "_id=?", new String[]{"5"});
                    // 受影响行数大于0就是成功了
                    if (result > 0) {
                        alterUser("修改成功");
                    }
                    db.close();
                    break;
                }
                case R.id.bt_delete: {
                    SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();
                    // SQL语句的方式
                    // db.execSQL("delete from student_table where _id = 1;");
    
                    // OOP面向对象的方式
                    int result = db.delete(MySQLiteOpenHelper.TABLE_NAME, "_id=?", new String[]{"6"});
                    // 受影响行数大于0就是成功了
                    if (result > 0) {
                        alterUser("删除成功");
                    }
                    db.close();
                    break;
                }
                default:
                    break;
            }
        }
    
        private void alterUser(String text) {
            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }
    }

    布局代码:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/bt_query"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查询"
            />
    
        <Button
            android:id="@+id/bt_insert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="插入"
            />
    
        <Button
            android:id="@+id/bt_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改"
            />
    
        <Button
            android:id="@+id/bt_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"
            />
    
    
    </LinearLayout>

     增删改查后的数据:

  • 相关阅读:
    Entity Framework Tips: IN关键字的支持
    (转载)用IT网络和安全专业人士视角来裁剪云的定义
    解决数据库查询中的锁冲突
    2010年计划
    MergeOption 枚举实测
    习惯的力量
    Entity Framewok中获取实体对象的部分属性
    JQuery下拉框联动本地数据
    Json学习整理
    Hadoop:mapreduce的splitsize和blocksize
  • 原文地址:https://www.cnblogs.com/android-deli/p/10085429.html
Copyright © 2011-2022 走看看