android 之 数据库操作

本文详细介绍了Android中SQLite数据库的基本使用方法,包括如何通过SQLiteOpenHelper创建数据库和表、执行增删改查等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于android而言,它为我们提供了一个十分强大的轻量级数据库。该数据库基本可以满足我们的需求,下面我们就来讲解一下SQLiteOpenHelper 以及SQLiteDatabase的用法: 由于 SQLiteOpenHelper是一个抽象类,所以我们要用一个实现类来实现它,旗下有两个方法需要我们适当的加入相应的逻辑,分别是oncrecateonupgrade方法。 当然,SQLiteOpenHelper 中 还 有 两 个 非 常 重 要 的 实 例方 法 , getReadableDatabase()getWritableDatabase()。这两个方法都可以创建或打开一个现有的数据库(如果数据库已存在则直接打开,否则创建一个新的数据库) ,并返回一个可对数据库进行读写操作的对象。不同的是当数据库不可写入的时候(如磁盘空间已满)getReadableDatabase()方法返回的对象将以只读的方## 标题 ##式去打开数据库,而 getWritableDatabase()方法则将出现异常。 下面,我们就通过代码来更深层次的来探讨,新建一个类MyDatabaseHelper使他继承SQLiteOpenHelper类,代码如下:

public class MyDatabaseHelper extends SQLiteOpenHelper {

        public static final String CREATE_BOOK = "create table Book ("
                     + "id integer primary key autoincrement, "
                     + "author text, "
                     + "price real, "
                     + "pages integer, "
                     + "name text)";

        public static final String CREATE_CATEGORY = "create table Category ("
                     + "id integer primary key autoincrement, "
                     + "category_name text, "
                     + "category_code integer)";

        public MyDatabaseHelper(Context context, String name,
                     CursorFactory factory, int version) {
               super(context, name, factory, version);
       }

        @Override
        public void onCreate(SQLiteDatabase db) {
              db.execSQL( CREATE_BOOK);
              db.execSQL( CREATE_CATEGORY);
       }

        @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);
       }

}
 *

首先我们建立了两条sql语句,分别创建了Book表和Catagory表,接着,将其逻辑赋值在oncreate方法中,则只要该类一经调用,便会去发现它,然后去判断是否该数据库已经存在该表格,若存在,不创建,若不存在,创建,及表只会别创建一次。我们再来看看onupgrade这个方法,用于表只会创建一次,但如果我们后面由于要加入新的需求怎么办,那么这时候就要用到这个onupgrade方法了,只需将其内置的版本号调为比当前版本号大即可执行到里面的逻辑。

*
一下是我们的 MainActivity中的主要逻辑。

public class MainActivity extends Activity {

        private MyDatabaseHelper dbHelper ;//通过DatabaseHelper来操作数据

        @Override
        protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
              setContentView(R.layout. activity_main);
               dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);//创建数据库
              Button createDatabase = (Button) findViewById(R.id. create_database);
              createDatabase.setOnClickListener( new OnClickListener() {
                      @Override
                      public void onClick(View v) {
                            dbHelper.getWritableDatabase(); //开始读写操作
                     }
              });
              Button addData = (Button) findViewById(R.id. add_data);
              addData.setOnClickListener( new OnClickListener() {
                      @Override
                      public void onClick(View v) {
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                           ContentValues values = new ContentValues();//用于存取数据
                           values.put( "name", "The Da Vinci Code" );
                           values.put( "author", "Dan Brown" );
                           values.put( "pages", 454);
                           values.put( "price", 16.96);
                           db.insert( "Book", null , values);
                           values.clear(); //清空数据
                           values.put( "name", "The Lost Symbol" );
                           values.put( "author", "Dan Brown" );
                           values.put( "pages", 510);
                           values.put( "price", 19.95);
                           db.insert( "Book", null , values);//插入数据到数据库中
                     }
              });
              Button updateData = (Button) findViewById(R.id. update_data);
              updateData.setOnClickListener( new OnClickListener() {//更新数据
                      @Override
                      public void onClick(View v) {
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                           ContentValues values = new ContentValues();
                           values.put( "price", 10.99);
                           db.update( "Book", values, "name = ?" ,
                                          new String[] { "The Da Vinci Code" });
                     }
              });
              Button deleteButton = (Button) findViewById(R.id. delete_data);//删除数据
              deleteButton.setOnClickListener( new OnClickListener() {
                      @Override
                      public void onClick(View v) {
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                           db.delete( "Book", "pages > ?" , new String[] { "500" });
                     }
              });
              Button queryButton = (Button) findViewById(R.id. query_data);//查询数据
              queryButton.setOnClickListener( new OnClickListener() {
                      @Override
                      public void onClick(View v) {
                           Uri uri = Uri
                                         . parse("content://com.example.databasetest.provider/book");
                           Cursor cursor = getContentResolver().query(uri, null, null,
                                          null, null );
                            if (cursor != null) {
                                   while (cursor.moveToNext()) {
                                         String name = cursor.getString(cursor
                                                       .getColumnIndex( "name"));
                                         String author = cursor.getString(cursor
                                                       .getColumnIndex( "author"));
                                          int pages = cursor.getInt(cursor
                                                       .getColumnIndex( "pages"));
                                          double price = cursor.getDouble(cursor
                                                       .getColumnIndex( "price"));
                                         Log. d("MainActivity", "book name is " + name);
                                         Log. d("MainActivity", "book author is " + author);
                                         Log. d("MainActivity", "book pages is " + pages);
                                         Log. d("MainActivity", "book price is " + price);
                                  }
                                  cursor.close();
                           }
                     }
              });
              Button replaceData = (Button) findViewById(R.id. replace_data);//对数据库进行事物处理
              replaceData.setOnClickListener( new OnClickListener() {
                      @Override
                      public void onClick(View v) {
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                           db.beginTransaction();
                            try {
                                  db.delete( "Book", null , null);
                                   // if (true) {
                                   // throw new NullPointerException();
                                   // }
                                  ContentValues values = new ContentValues();
                                  values.put( "name", "Game of Thrones" );
                                  values.put( "author", "George Martin" );
                                  values.put( "pages", 720);
                                  values.put( "price", 20.85);
                                  db.insert( "Book", null , values);
                                  db.setTransactionSuccessful();
                           } catch (Exception e) {
                                  e.printStackTrace();
                           } finally {
                                  db.endTransaction();
                           }
                     }
              });
       }

}

*在这个类中,我想你也大概能看得懂,其主要是做了增删改查的操作,通过 SQLiteDatabase 这个类来实现,这里由于和java对数据库中的操作大同小异就不在进行废话,更多详情,你可以去看第一行代码中的介绍。
下面是我们的activity_main.xml的代码:*

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width= "match_parent"
    android:layout_height= "match_parent"
    android:orientation= "vertical" >

    <Button
        android:id="@+id/create_database"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create database" />

    <Button
        android:id="@+id/add_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add data" />

    <Button
        android:id="@+id/update_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Update data" />

    <Button
        android:id="@+id/delete_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete data" />

    <Button
        android:id="@+id/query_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Query data" />

    <Button
        android:id="@+id/replace_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace data" />

</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值