• android——SQLite数据库存储(操作)


     1 public class MyDatabaseHelper extends SQLiteOpenHelper {
     2 
     3     //把定义SQL建表语句成字符串常量
     4 
     5     //图书的详细信息
     6     //ID、作者、价格、页数、书名
     7     public static final String CREATE_BOOK = "create table Book("
     8             +"id integer primary key autoincrement,"
     9             +"author text,"
    10             +"price real,"
    11             +"pages integer,"
    12             +"name text)";
    13 
    14     private Context mContext;
    15 
    16     //构造方法
    17     public MyDatabaseHelper(Context context, String name,
    18                             SQLiteDatabase.CursorFactory factory, int version){
    19         super(context,name,factory,version);
    20         mContext = context;
    21     }
    22 
    23     //建表
    24     @Override
    25     public void onCreate(SQLiteDatabase db) {
    26         db.execSQL(CREATE_BOOK);
    27         Toast.makeText(mContext,"数据库创建成功", Toast.LENGTH_SHORT).show();
    28     }
    29 
    30     @Override
    31     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    32     }
    33 }

      目前数据库中有一个Book表,如果想要添加一个Category表,就需要对数据库进行升级,这时需要用到MyDatabaseHelper中的onUpgrade()方法。

      首先和Book表的建立一样需要先写好建表语句:

      create table Category (

        id integer primary key autoincrement

        category_name text

        category_code integer)

      修改后的代码如下:

    public class MyDatabaseHelper extends SQLiteOpenHelper {
    
        //把定义SQL建表语句成字符串常量
    
        //图书的详细信息
        //ID、作者、价格、页数、书名
        public static final String CREATE_BOOK = "create table Book("
                +"id integer primary key autoincrement,"
                +"author text,"
                +"price real,"
                +"pages integer,"
                +"name text)";
    
        //图书的分类
        //图书的id、分类名、分类代码
        public static final String CREATE_CATEGORY = "create table Category("
                + "id integer primary key autoincrement,"
                + "category_name text,"
                + "category_code inter)";
    
        private Context mContext;
    
        //构造方法
        public MyDatabaseHelper(Context context, String name,
                                SQLiteDatabase.CursorFactory factory, int version){
            super(context,name,factory,version);
            mContext = context;
        }
    
        //建表
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_BOOK);
            db.execSQL(CREATE_CATEGORY);
            Toast.makeText(mContext,"数据库创建成功", Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            db.execSQL("drop table if exists Book");
            db.execSQL("drop table if exists Category");
            onCreate(db);
        }
    }

      在onUpgrade()方法中先使用drop语句如果已经存在Book表和Category表,就把两张表都删掉,因为数据库已经存在了,onCreate()方法怎么样都不会再执行的。

      然后在MainActivity修改代码:

     1 public class MainActivity extends AppCompatActivity {
     2 
     3     private MyDatabaseHelper dbHelper;
     4 
     5     @Override
     6     protected void onCreate(Bundle savedInstanceState) {
     7         super.onCreate(savedInstanceState);
     8         setContentView(R.layout.activity_main);
     9 
    10         //创建帮助类的实例
    11         dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);
    12 
    13         //注册按钮
    14         Button creatDatabase = (Button) findViewById(R.id.creat_database);
    15         //按钮响应
    16         creatDatabase.setOnClickListener(new View.OnClickListener() {
    17             @Override
    18             public void onClick(View view) {
    19                 dbHelper.getWritableDatabase();
    20             }
    21         });
    22 23
      dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);把最后一个参数从之前的1改为2,再按下创建数据库就可完成升级。
      接下来完成数据库的添加、更新、删除、查询操作。
      先修改布局文件添加4个按钮:
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     android:orientation="vertical">
     6 
     7     <Button
     8         android:id="@+id/creat_database"
     9         android:layout_width="match_parent"
    10         android:layout_height="wrap_content"
    11         android:text="建立数据库"/>
    12 
    13     <Button
    14         android:id="@+id/add_data"
    15         android:layout_width="match_parent"
    16         android:layout_height="wrap_content"
    17         android:text="添加数据"/>
    18 
    19     <Button
    20         android:id="@+id/updata_data"
    21         android:layout_width="match_parent"
    22         android:layout_height="wrap_content"
    23         android:text="更新数据"/>
    24 
    25     <Button
    26         android:id="@+id/delete_data"
    27         android:layout_width="match_parent"
    28         android:layout_height="wrap_content"
    29         android:text="删除数据"/>
    30 
    31     <Button
    32         android:id="@+id/query_data"
    33         android:layout_width="match_parent"
    34         android:layout_height="wrap_content"
    35         android:text="查询数据"/>
    36 </LinearLayout>

      在MainActivity中这样完成:

     1 public class MainActivity extends AppCompatActivity {
     2 
     3     private MyDatabaseHelper dbHelper;
     4 
     5     @Override
     6     protected void onCreate(Bundle savedInstanceState) {
     7         super.onCreate(savedInstanceState);
     8         setContentView(R.layout.activity_main);
     9 
    10         //创建帮助类的实例
    11         dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);
    12 
    13         //注册按钮
    14         Button creatDatabase = (Button) findViewById(R.id.creat_database);
    15         Button adddata = (Button) findViewById(R.id.add_data);
    16         Button updataData = (Button) findViewById(R.id.updata_data);
    17         Button deleteData = (Button) findViewById(R.id.delete_data);
    18         Button queryData = (Button) findViewById(R.id.query_data);
    19         //按钮响应
    20         creatDatabase.setOnClickListener(new View.OnClickListener() {
    21             @Override
    22             public void onClick(View view) {
    23                 dbHelper.getWritableDatabase();
    24             }
    25         });
    26 
    27         //添加数据
    28         adddata.setOnClickListener(new View.OnClickListener() {
    29             @Override
    30             public void onClick(View view) {
    31                 SQLiteDatabase db = dbHelper.getWritableDatabase();
    32                 ContentValues values = new ContentValues();
    33                 //第一条数据
    34                 values.put("name","The Da Vinci Code");
    35                 values.put("author","Dan Brown");
    36                 values.put("pages",45);
    37                 values.put("price",16.96);
    38                 db.insert("Book",null,values);
    39                 values.clear();
    40                 //第二条数据
    41                 values.put("name","The Lost symbol");
    42                 values.put("author","Dan Brown");
    43                 values.put("pages",510);
    44                 values.put("price",19.95);
    45                 db.insert("Book",null,values);
    46                 Toast.makeText(MainActivity.this,"添加数据成功",Toast.LENGTH_SHORT).show();
    47             }
    48         });
    49 
    50         //更新数据
    51         updataData.setOnClickListener(new View.OnClickListener() {
    52             @Override
    53             public void onClick(View view) {
    54                 SQLiteDatabase db = dbHelper.getWritableDatabase();
    55                 ContentValues values = new ContentValues();
    56                 values.put("price",10.899);
    57                 db.update("Book", values, "name = ?",new String[] {"The Da Vinci Code"});
    58             }
    59         });
    60 
    61         //删除数据
    62         deleteData.setOnClickListener(new View.OnClickListener() {
    63             @Override
    64             public void onClick(View view) {
    65                 SQLiteDatabase db = dbHelper.getWritableDatabase();
    66                 db.delete("Book","pages > ?",new String[] {"500"});
    67             }
    68         });
    69 
    70         //查询数据
    71         queryData.setOnClickListener(new View.OnClickListener() {
    72             @Override
    73             public void onClick(View view) {
    74                 SQLiteDatabase db = dbHelper.getWritableDatabase();
    75                 Cursor cursor = db.query("Book", null, null ,null, null, null, null );
    76                 if(cursor.moveToFirst()){
    77                     String name = cursor.getString(cursor.getColumnIndex("name"));
    78                     String author = cursor.getString(cursor.getColumnIndex("author"));
    79                     int pages = cursor.getInt(cursor.getColumnIndex("pages"));
    80                     double price = cursor.getDouble(cursor.getColumnIndex("price"));
    81                     Log.d("MainActivity","book name is " + name);
    82                     Log.d("MainActivity","book auther is " + author);
    83                     Log.d("MainActivity","book pagesis " + pages);
    84                     Log.d("MainActivity","book price is " + price);
    85                 }
    86             }
    87         });
    88     }
    89 }

      添加数据:先使用dbHelper.getWritableDatabase()方法创建一个SQLiteDatabase的实例db,用于操作数据库,然后创键一个ContentValues的实例values,用来存放要添加的数据。然后是要values的put()方法将数据存入values中,再使用db的insert()方法将数据添加进数据库。然后使用clear()方法清空values再添加下一个数据。最后提醒添加成功。

      更新数据:一样使用dbHelper.getWritableDatabase()创建一个一个SQLiteDatabase的实例db,在创建一个values,将要更新的数据存放在values中,然后使用update()方法更新数据。第三个和第四个参数用于判断修改的是哪一行的数据。

      删除数据:使用delete()方法,第一个参数是想要操作的表名,第二个第三个指定操作的行。

      查询数据:将数据存放在cursor对象中,query()方法最短也要有7个参数,例如:(返回值)方法名:query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy),其中table指定想要查询的表名,columns指定查询的列名,selection指定where的约束条件,selectionArgs为where中的占位符提供具体的值,groupBy指定group by的列,having对group by后的结果进行约束,orderBy查询结果的排序方式。

      db.query("Book", null, null ,null, null, null, null );这样的用法表示将遍历整个Book表。

      然后使用cursor的moveToFirst方法将指针移到第一行,再一次向下移动实现遍历,再使用cursor.getColumnIndex()方法得到相应列的索引,通过getString、getInt、getDouble获得相应类型的数据,最后输出查询的结果。

  • 相关阅读:
    关于findViewById返回空指针的错误
    android客户端向服务器发送图片和文字,类似于发微博。能用json格式发送吗?
    nodejs 学习资料大全
    篇章三:[AngularJS] 使用AngularCSS動態載入CSS
    篇章二:[AngularJS] 使用AngularAMD動態載入Service
    篇章一:[AngularJS] 使用AngularAMD動態載入Controller
    Angular 资料大集合
    js-音乐播放器,播放|暂停|滑块的功能
    JS-以鼠标位置为中心的滑轮放大功能demo1
    使用 Electron 构建桌面应用(拖动控制篇)
  • 原文地址:https://www.cnblogs.com/xxbbtt/p/7435933.html
Copyright © 2020-2023  润新知