赞
踩
本文对数据库的建立、更新,数据的插入、更新、查询、删除,及事务的处理进行示例讲解。
代码里有注释帮助理解。
- <?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:id="@+id/activity_main"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context="com.example.administrator.dbexcise.MainActivity">
-
- <Button
- android:id="@+id/bt1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Create DB"
- android:textAllCaps="false"
- android:onClick="testCreateDB"/>
-
- <Button
- android:id="@+id/bt2"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Insert Date"
- android:textAllCaps="false"
- android:onClick="testInsertDate"/>
-
- <Button
- android:id="@+id/bt3"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Delete Date"
- android:textAllCaps="false"
- android:onClick="testDeleteDate"/>
-
- <Button
- android:id="@+id/bt4"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Update Date"
- android:textAllCaps="false"
- android:onClick="testUpdateDate"/>
-
- <Button
- android:id="@+id/bt5"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Query Date"
- android:textAllCaps="false"
- android:onClick="testQueryDate"/>
-
- <Button
- android:id="@+id/bt6"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Handle affair"
- android:textAllCaps="false"
- android:onClick="testHandleAffair"/>
- </LinearLayout>
- package com.example.administrator.dbexcise.database;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.util.Log;
-
- /**
- * Created by Administrator on 2019/6/19.
- */
-
- public class DBHelper extends SQLiteOpenHelper {
-
- public DBHelper(Context context, int version) {
- //上下文,数据库文件名,null,版本号
- super(context, "person.db", null, version);
- }
-
- /**
- * 什么时候调用?
- * 当数据库文件创建时调用
- * 在此方法中做什么?
- * 建表,初始化数据
- * @param sqLiteDatabase 是操作数据库的对象
- */
- @Override
- public void onCreate(SQLiteDatabase sqLiteDatabase) {
- Log.e("TAG", "onCreate: " );
-
- String sql = "create table person (_id integer primary key autoincrement,name varchar,age int)";
- sqLiteDatabase.execSQL(sql);
- }
-
- /**
- * 当传入的版本号大于当前数据库的版本号时调用
- * 用于更新数据库
- * @param sqLiteDatabase
- * @param i
- * @param i1
- */
- @Override
- public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
- Log.d("TAG", "onUpgrade: ");
- }
- }
- package com.example.administrator.dbexcise;
-
- import android.content.ContentValues;
- import android.content.Intent;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
-
- import com.example.administrator.dbexcise.database.DBHelper;
-
- public class MainActivity extends AppCompatActivity {
-
- Button button, button2, button3, button4, button5, button6;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- button = (Button) findViewById(R.id.bt1);
- button2 = (Button) findViewById(R.id.bt2);
- button3 = (Button) findViewById(R.id.bt3);
- button4 = (Button) findViewById(R.id.bt4);
- button5 = (Button) findViewById(R.id.bt5);
- button6 = (Button) findViewById(R.id.bt6);
- }
-
- /**
- * 创建库
- *
- * @param view
- */
- public void testCreateDB(View view) {
- DBHelper dbHelper = new DBHelper(this, 1);
- //获取连接
- SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
-
- Toast.makeText(this, "创建数据库", Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 插入数据
- *
- * @param view
- */
- public void testInsertDate(View view) {
- DBHelper dbHelper = new DBHelper(this,2);
- //1.得到连接
- SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
-
- //2.执行insert
- ContentValues values = new ContentValues();
- values.put("name","Tom");
- values.put("age",21);
- //返回插入的id
- /**
- * 第一个参数:表名
- * 第二个参数:null
- * 第三个参数:传入的HashMap值
- */
- long id = sqLiteDatabase.insert("person",null,values);
-
- //3.关闭连接
- sqLiteDatabase.close();
-
- //4.提示
- Toast.makeText(this,"id= "+id,Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 删除数据
- *
- * @param view
- */
- public void testDeleteDate(View view) {
- DBHelper dbHelper = new DBHelper(this,2);
- //1.得到连接
- SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
-
- //2.执行delete
- String where = "name = ?";
- String[] value = new String[]{ "Tom" };
- //返回删除的数量
- /**
- * 第一个参数:表名
- * 第二个参数:删除的where后的语句
- * 第三个参数:? 所代表的值
- */
- int deleteCount = sqLiteDatabase.delete("person",where,value);
-
- //3.关闭连接
- sqLiteDatabase.close();
-
- //4.提示
- Toast.makeText(this,"deleteCount = "+deleteCount,Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 更新数据
- *
- * @param view
- */
- public void testUpdateDate(View view) {
- DBHelper dbHelper = new DBHelper(this,2);
- //1.得到连接
- SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
-
- //2.执行update update person set name = "Jack",age = 20 where _id = 6
-
- /**
- * 第一个参数:表名
- * 第二个参数:更新的value
- * 第三个参数:where 后的语句
- * 第四个参数:? 所代表的值
- */
- ContentValues values = new ContentValues();
- values.put("name","Jack");
- values.put("age",20);
- int updateCount = sqLiteDatabase.update("person",values,"_id = 6",null);
-
- //3.关闭连接
- sqLiteDatabase.close();
-
- //4.提示
- Toast.makeText(this,"updateCount = "+updateCount,Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 查询数据
- *
- * @param view
- */
- public void testQueryDate(View view) {
- DBHelper dbHelper = new DBHelper(this,2);
- //1.得到连接
- SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
-
- //2.执行query select * from person
- Cursor cursor = sqLiteDatabase.query("person",null,null,null,null,null,null);
- //得到cursor查询到的总记录数
- int count = cursor.getCount();
-
- while(cursor.moveToNext()){
- // id
- int id = cursor.getInt(0);
-
- // name
- String name = cursor.getString(1);
-
- // age
- int age = cursor.getInt(cursor.getColumnIndex("age"));
- }
-
- //3.关闭连接
- cursor.close();
- sqLiteDatabase.close();
-
- //4.提示
- Toast.makeText(this,"count = "+count,Toast.LENGTH_SHORT).show();
- }
-
- /**
- * 事务处理
- *
- * 一个功能中对数据库进行多个操作,要就都成功要就都失败
- * 事务处理三步骤:
- * 1. 开启事务(获取连接后)
- * 2. 设置事务成功(在全部正常执行完后)
- * 3. 结束事务(finally中进行)
- *
- * @param view
- */
- public void testHandleAffair(View view) {
- SQLiteDatabase sqLiteDatabase = null;
- try {
- DBHelper dbHelper = new DBHelper(this,2);
- //1.得到连接
- sqLiteDatabase = dbHelper.getReadableDatabase();
-
- //1. 开启事务(获取连接后)
- sqLiteDatabase.beginTransaction();
-
- //2.执行update update person set age = 20 where _id = 6
- ContentValues values = new ContentValues();
- values.put("age",20);
- int updateCount = sqLiteDatabase.update("person",values,"_id = 6",null);
-
- boolean flag = true;
- if(flag) {
- throw new RuntimeException("出异常啦!!");
- }
-
- //执行update update person set age = 21 where _id = 7
- values.put("age",21);
- int updateCount2 = sqLiteDatabase.update("person",values,"_id = 7",null);
-
- //2.设置事务成功(在全部正常执行完后)
- sqLiteDatabase.setTransactionSuccessful();
- }catch (Exception e) {
- Toast.makeText(this,"出异常啦!!!",Toast.LENGTH_SHORT).show();
- }finally {
- if (sqLiteDatabase!=null) {
- //3.结束事务(finally中进行)
- sqLiteDatabase.endTransaction();
- //3.关闭连接
- sqLiteDatabase.close();
- }
- }
- }
- }
注意:new一个数据库对象后,一定要获取连接再进行操作。
链接:https://pan.baidu.com/s/1TwNX_V0pI-yPSBFqJpm9DA
提取码:hnz2
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。