数据库事务
layout代码:
<?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" android:orientation="vertical" tools:context="com.example.my.testapp.TestActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="初始化数据库" android:onClick="bt_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="升级数据库" android:onClick="bt1_onClick"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/et_id" android:hint="id"/> <EditText android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/et_name" android:hint="name"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/et_sex" android:hint="sex"/> <EditText android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/et_age" android:hint="age"/> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="新增数据" android:onClick="bt2_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询数据" android:onClick="bt3_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="带条件查询数据" android:onClick="bt4_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="修改数据" android:onClick="bt5_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="删除数据" android:onClick="bt6_onClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="数据库事务" android:onClick="bt7_onClick"/> </LinearLayout>
Activity代码:
package com.example.my.testapp; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class TestActivity extends AppCompatActivity { EditText et_id,et_name,et_sex,et_age; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); et_id=(EditText)findViewById(R.id.et_id); et_name=(EditText)findViewById(R.id.et_name); et_sex=(EditText)findViewById(R.id.et_sex); et_age=(EditText)findViewById(R.id.et_age); } //初始化数据库 public void bt_onClick(View v) { //使用工具类得到数据库对象 MyDBHelper myDBHelper=new MyDBHelper("test.db",1); //得到连接 SQLiteDatabase sqLiteDatabase=myDBHelper.getWritableDatabase(); Toast.makeText(TestActivity.this, "连接数据库成功", Toast.LENGTH_SHORT).show(); //关闭连接 sqLiteDatabase.close(); } public void bt1_onClick(View v) { //使用工具类得到数据库对象 MyDBHelper myDBHelper=new MyDBHelper("test.db",2); //得到连接 SQLiteDatabase sqLiteDatabase=myDBHelper.getWritableDatabase(); Toast.makeText(TestActivity.this, "连接数据库成功", Toast.LENGTH_SHORT).show(); //关闭连接 sqLiteDatabase.close(); } //插入新数据 public void bt2_onClick(View v) { //1.连接数据库,得到数据库连接对象 //得到连接 SQLiteDatabase sqLiteDatabase=new MyDBHelper("test.db",2).getWritableDatabase(); //2.准备数据 ContentValues cv=new ContentValues(); cv.put("name",et_name.getText().toString()); cv.put("sex",et_sex.getText().toString()); cv.put("age",et_age.getText().toString()); //3.调用插入数据 long l=sqLiteDatabase.insert("t_user", null, cv); Toast.makeText(TestActivity.this, "插入的数据主键="+l, Toast.LENGTH_SHORT).show(); //4.关闭连接 sqLiteDatabase.close(); } //数据查询 public void bt3_onClick(View v) { //1.连接数据库,得到数据库连接对象 //得到连接 SQLiteDatabase sqLiteDatabase=new MyDBHelper("test.db",2).getWritableDatabase(); //2.全表全字段查询 Cursor c=sqLiteDatabase.query("t_user", null, null, null, null, null, null); //3.遍历结果集 while (c.moveToNext()) { //读取数据 String str=c.getLong(c.getColumnIndex("_id"))+" name = "+c.getString(1)+" sex = "+c.getString(2) +" age= "+c.getString(c.getColumnIndex("age")); Log.e("TAG",str); } Toast.makeText(TestActivity.this, "结果集的条数"+c.getCount(), Toast.LENGTH_SHORT).show(); c.close(); //4.关闭连接 sqLiteDatabase.close(); } public void bt4_onClick(View v) { //1.连接数据库,得到数据库连接对象 //得到连接 SQLiteDatabase sqLiteDatabase=new MyDBHelper("test.db",2).getWritableDatabase(); String strwhere="1=1"; //select * from t_user where 1=1 and _id =1 and name like '%张%' //得到条件 if (et_id.getText().length()>0) { strwhere += " and _id= "+et_id.getText().toString(); } if (et_name.getText().length()>0) { strwhere += " and name like '%"+et_name.getText().toString()+"%'"; } if (et_sex.getText().length()>0) { strwhere += " and sex = '"+et_id.getText().toString()+"'"; } if (et_age.getText().length()>0) { strwhere += " and age = "+et_id.getText().toString(); } //2.全表全字段查询 Cursor c=sqLiteDatabase.query("t_user", null, strwhere, null, null, null, null); //3.遍历结果集 while (c.moveToNext()) { //读取数据 String str=c.getLong(c.getColumnIndex("_id"))+" name = "+c.getString(1)+" sex = "+c.getString(2) +" age= "+c.getString(c.getColumnIndex("age")); Log.e("TAG",str); } Toast.makeText(TestActivity.this, "结果集的条数"+c.getCount(), Toast.LENGTH_SHORT).show(); c.close(); //4.关闭连接 sqLiteDatabase.close(); } public void bt5_onClick(View v) { //1.连接数据库,得到数据库连接对象 //得到连接 SQLiteDatabase sqLiteDatabase=new MyDBHelper("test.db",2).getWritableDatabase(); //2.修改 ContentValues cv=new ContentValues(); cv.put("name",et_name.getText().toString()); cv.put("name",et_sex.getText().toString()); cv.put("name", et_age.getText().toString()); int i=sqLiteDatabase.update("t_user", cv, "_id=?", new String[]{et_id.getText().toString()}); Toast.makeText(TestActivity.this, "修改的记录条数"+i, Toast.LENGTH_SHORT).show(); //4.关闭连接 sqLiteDatabase.close(); } public void bt6_onClick(View v) { //1.连接数据库,得到数据库连接对象 //得到连接 SQLiteDatabase sqLiteDatabase=new MyDBHelper("test.db",2).getWritableDatabase(); //2.删除 int i=sqLiteDatabase.delete("t_user", "_id=?", new String[]{et_id.getText().toString()}); Toast.makeText(TestActivity.this, "修改的记录条数"+i, Toast.LENGTH_SHORT).show(); //4.关闭连接 sqLiteDatabase.close(); } public void bt7_onClick(View v) { //1.连接数据库,得到数据库连接对象 SQLiteDatabase sqLiteDatabase = new MyDBHelper("test.db", 2).getWritableDatabase(); try { //得到连接 //启动事务 sqLiteDatabase.beginTransaction(); //2.修改 ContentValues cv = new ContentValues(); cv.put("age", "43"); //修改1 int i = sqLiteDatabase.update("t_user", cv, "_id=1", null); //抛出异常 // if (i > 0) { // throw new RuntimeException("模拟事务异常"); // } ContentValues cv2 = new ContentValues(); cv2.put("age", "53"); //修改2 int k = sqLiteDatabase.update("t_user", cv2, "_id=2", null); //设置事务是成功完成的 sqLiteDatabase.setTransactionSuccessful(); Toast.makeText(TestActivity.this, "修改的记录条数" + (i + k), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(TestActivity.this, "修改出错", Toast.LENGTH_SHORT).show(); } finally { //一定会被执行代码 //结束事务 //1.没有异常,提交事务 //2.发生异常,回滚事务 sqLiteDatabase.endTransaction(); //4.关闭连接 sqLiteDatabase.close(); } } //实现SQLiteOpenHelper内部类 class MyDBHelper extends SQLiteOpenHelper { //构造方法 public MyDBHelper(String dbname,int ver) { //显示调用父类的构造方法 //必须在第一行 super(TestActivity.this,dbname,null,ver); } //初始化数据库 @Override public void onCreate(SQLiteDatabase db) { //1.执行创建数据库的语句 String sql = "CREATE TABLE \"main\".\"t_user\" " + "(\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "\"name\" VARCHAR(20),\"sex\" CHAR(1)," + "\"age\" INTEGER)"; db.execSQL(sql); Log.e("TAG","表创建成功"); //2.初始化数据的语句 insert语句 sql=""; ContentValues contentValues = new ContentValues(); contentValues.put("name","张全蛋"); contentValues.put("sex","男"); contentValues.put("age","20"); //执行插入,返回主键 long l=db.insert("t_user",null,contentValues); Log.e("TAG","初始化数据 = "+1); } //升级数据库 //触发条件:当版本号变大 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //修改数据 if (newVersion ==2) { //调用db的更新方法 ContentValues cv=new ContentValues(); cv.put("name", "李狗蛋"); String sql="update t_user set name='李狗蛋' where _id=1"; String[] str={"1","18"}; int i=db.update("t_user",cv,"_id=? and age > ?",str); Log.e("TAG","升级数据 数据条数="+i); } } } }