• Android课程---关于数据存储的学习(3)之数据库和事务


    DataActivity3.java

    package com.hanqi.test5;
    
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    
    public class DataActivity3 extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_data3);
        }
    
        //继承SQLiteOpenHelper
        class DBHelper extends SQLiteOpenHelper
        {
            //构造方法
            //name  数据库名
            //version  所创建的数据库版本号
            public DBHelper(String name,int version) {
                //调用父类的构造方法,写在第一行
                super(DataActivity3.this, name, null, version);
            }
    
            //在创建数据库时调用
            //回调方法
            //什么时候创建数据库:连接数据库的时候,如果数据文件不存在
            //只调用一次
            @Override
            public void onCreate(SQLiteDatabase db) {
    
                //1.创建数据库的语句
                String creatTable = "create table user(_id integer PRIMARY KEY AUTOINCREMENT NOT NULL,name varchar,age int)";
                db.execSQL(creatTable);
    
                //2.初始化数据
                ContentValues cv = new ContentValues();
    
                cv.put("name","房崇延");
    
                cv.put("age", 20);
    
                //如果不成功返回-1
                //第一个参数是表名
                //第二个参数是空列的默认值
                //第三个参数是字段和值的集合(key/value)
                long l = db.insert("user",null,cv);
    
                Toast.makeText(DataActivity3.this, "id = "+ l, Toast.LENGTH_LONG).show();
    
            }
    
            //升级数据库
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
               //执行升级
                //update user set age = 27 where _id = ?
                //? 是占位符,然后给占位符赋值
                ContentValues cv = new ContentValues();
    
                cv.put("age", 27);
    
                int rowcount = db.update("user",cv,"_id=? and name=?",new String[]{"1","TOM"});
                Log.e("TAG","rowcount = "+rowcount);
    
            }
        }
    
        //创建数据库
        public void dt1_OnClick(View v)
        {
            //创建
            DBHelper dh = new DBHelper("test.db",1);
            //获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
            sd.close();
        }
        //升级数据库
        public void dt2_OnClick(View v)
        {
           //创建  实现工具类
            DBHelper dh = new DBHelper("test.db",2);
    
            //连接数据库  获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
            sd.close();
        }
        //插入数据
        public void dt3_OnClick(View v)
        {
            //创建
            DBHelper dh = new DBHelper("test.db",2);
            //获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
    
            ContentValues cv = new ContentValues();
            cv.put("name","房子");
            cv.put("age", "18");
    
            long _id = sd.insert("user", null, cv);
    
            Log.e("TAG","_id = " + _id);
    
            sd.close();
        }
        //修改数据
        public void dt5_OnClick(View v)
        {
            //创建
            DBHelper dh = new DBHelper("test.db",2);
            //获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
    
            ContentValues cv = new ContentValues();
            cv.put("name","房子1");
    
            int count = sd.update("user", cv, "_id >=3", null);
    
            Log.e("TAG", "updatecount = " + count);
    
            sd.close();
        }
        //修改数据2
        public void dt7_OnClick(View v)
        {
            //创建
            DBHelper dh = new DBHelper("test.db",2);
            //获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
    
            //没有工具类时可以用下面这个方法  但是很繁琐
            // 连接
            //sd = SQLiteDatabase.openOrCreateDatabase("test.db",null);
            //判断是否建表了,是否升级了  不如工具类好用
    
            try {
                //1.开启事务
                sd.beginTransaction();
    
                ContentValues cv = new ContentValues();
                cv.put("age", "50");
    
                int count = sd.update("user", cv, "_id =2", null);
    
                //抛出异常
                boolean b = true;
                if (b) {
                    throw new RuntimeException("出现异常了");
                }
    
                count += sd.update("user", cv, "_id =3", null);
    
                Log.e("TAG", "updatecount = " + count);
    
                //2.设置事务执行成功
                sd.setTransactionSuccessful();
                //提交
            }
            catch (Exception e)
            {
                //回滚
                e.printStackTrace();
    
                Toast.makeText(DataActivity3.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
    
            //一定会被执行的代码
            finally {
    
    
            //3.结束事务,1)提交  2)回滚
            sd.endTransaction();
    
            sd.close();
            }
        }
        //删除数据
        public void dt6_OnClick(View v)
        {
            //创建
            DBHelper dh = new DBHelper("test.db",2);
            //获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
    
            ContentValues cv = new ContentValues();
    
            int count = sd.delete("user","_id =4",null);
    
            Log.e("TAG", "deletecount = " + count);
    
            sd.execSQL("delete from user where _id =3");
    
            sd.close();
        }
        //查询数据
        public void dt4_OnClick(View v)
        {
            //创建
            DBHelper dh = new DBHelper("test.db",2);
            //获取数据库实例
            SQLiteDatabase sd = dh.getWritableDatabase();
            //全表查询
            Cursor cursor = sd.query("user", null, null, null, null, null, null);
    
            //Cursor 一开始会定位在第一条数据的上方
            //移动游标到数据的上面,提取数据后,再继续移动
    
            while (cursor.moveToNext())
            {
                //cursor.getInt(0);
                 long _id = cursor.getLong(cursor.getColumnIndex("_id"));
                // 不知道具体列时,可以用这个相对麻烦的方法
    
                String name = cursor.getString(cursor.getColumnIndex("name"));
                int age = cursor.getInt(2);
    
                Log.e("TAG", "_id = " + _id + "name =" + name + "age = " + age);
    
            }
            cursor.close();
    
            sd.close();
        }
    }

    activity_data3.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.hanqi.test5.DataActivity3"
        android:orientation="vertical">
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="创建数据库"
            android:onClick="dt1_OnClick"
            android:id="@+id/dt_1"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="升级数据库"
            android:onClick="dt2_OnClick"
            android:id="@+id/dt_2"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="增加数据"
            android:onClick="dt3_OnClick"
            android:id="@+id/dt_3"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="查询数据"
            android:onClick="dt4_OnClick"
            android:id="@+id/dt_4"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="修改数据"
            android:onClick="dt5_OnClick"
            android:id="@+id/dt_5"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="删除数据"
            android:onClick="dt6_OnClick"
            android:id="@+id/dt_6"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="事务操作"
            android:onClick="dt7_OnClick"
            android:id="@+id/dt_7"/>
    
    
    
    
    </LinearLayout>

    效果图:

  • 相关阅读:
    为什么要用&lt;!DOCTYPE&gt;声明
    [asp.net core] Tag Helpers 简介(转)
    asp.net core输出中文乱码的问题
    探索Aspnetcore+mysql+efcore
    [Redis]发布/订阅
    [Centos 6]升级安装GCC(2)
    [Centos]升级安装GCC
    [小程序]那些icons
    初探微信小程序
    [CentOs7]搭建ftp服务器(3)——上传,下载,删除,重命名,新建文件夹
  • 原文地址:https://www.cnblogs.com/0927wyj/p/5401921.html
Copyright © 2020-2023  润新知