新思想

SQLite

SQLite

activity_main.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"
    android:orientation="vertical"
    tools:context="com.xiesir.example18sqlite.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提示信息" />

    <EditText
        android:id="@+id/etResult"
        android:minLines="5"
        android:text="已在 contacts.db 数据库中建立了 person 表:\n
create table person(_id integer primary key autoincrement, name char(10), phone char(18), salary integer(9))"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:orientation="horizontal"
        android:paddingLeft="0dp"
        android:paddingRight="0dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:text="增加"
            android:onClick="insertClick"
            android:layout_width="60dp"
            android:layout_height="wrap_content" />
        <Button
            android:text="删除"
            android:onClick="deleteClick"
            android:layout_width="60dp"
            android:layout_height="wrap_content" />
        <Button
            android:text="修改"
            android:onClick="updateClick"
            android:layout_width="60dp"
            android:layout_height="wrap_content" />
        <Button
            android:text="查询"
            android:onClick="selectClick"
            android:layout_width="60dp"
            android:layout_height="wrap_content" />
        <Button
            android:text="事务"
            android:onClick="transactionClick"
            android:layout_width="60dp"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

appOpenHelper.java:

package com.xiesir.example18sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by xiegly on 2016/5/30.
 */
public class appOpenHelper extends SQLiteOpenHelper {

    public appOpenHelper(Context context) {
        // arg1:上下文
        // arg2:数据库文件名
        // arg3:游标工厂,游标等同于结果集,传null使用默认工厂
        // arg4:版本,不能小于1,用于升级
        super(context, "contacts.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建表
        db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(18), salary integer(9))");
    }

    // 升级数据库时调用
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("appOpenHelper", "数据库升级");
    }
}

MainActivity.java:

package com.xiesir.example18sqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private appOpenHelper oh;
    private SQLiteDatabase db;
    private EditText etResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etResult = (EditText) findViewById(R.id.etResult);

        // 获取虚拟上下文
        oh = new appOpenHelper(getApplicationContext());
        // 如果数据库不存在,先创建,再打开,如果存在,就直接打开
        db = oh.getWritableDatabase();
        db.execSQL("delete from person");
    }

    public void display() {
        Cursor result = db.rawQuery("select * from person", null);
        etResult.setText("");
        // 把指针移动至下一行
        while (result.moveToNext()) {
            // 先通过列名,获取列索引,然后再获取该列的内容
            String name = result.getString(result.getColumnIndex("name"));
            String phone = result.getString(result.getColumnIndex("phone"));
            int salary = result.getInt(result.getColumnIndex("salary"));
            etResult.append(name + " ; " + phone + " ; " + salary + "\n");
        }
    }

    public void insertClick(View v) {
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"孙悟空", "13851685168", 28000});
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"朱八戒", "13858687898", 18000});
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"撒和尚", "13851285218", 15800});

        // by API
        ContentValues values = new ContentValues();
        values.put("name", "关云长");
        values.put("phone", "13891589158");
        values.put("salary", "21800");
        // 返回插入序号。若插入失败,返回值-1;
        long l = db.insert("person", null, values);
        values.put("name", "张飞");
        values.put("phone", "13851985198");
        values.put("salary", "20800");
        // 返回插入序号。若插入失败,返回值-1;
        l = db.insert("person", null, values);

        display();
    }

    public void deleteClick(View v) {
        db.execSQL("delete from person where name = ?", new Object[]{"撒和尚"});

        // 返回删除数
        int i = db.delete("person", "name = ?", new String[]{"张飞"});

        display();
    }

    public void updateClick(View v) {
        db.execSQL("update person set salary = ? where name = ?", new Object[]{18600, "朱八戒"});

        ContentValues values = new ContentValues();
        values.put("salary", "25800");
        int i = db.update("person", values, "name = ?", new String[]{"关云长"});

        display();
    }

    public void selectClick(View v) {
        Cursor cursor = db.rawQuery("select * from person", null);

        // arg1: 查询的字段
        // arg2: 查询的where条件
        // arg3: where条件的占位符
        cursor = db.query("person", null, null, null, null, null, null, null);
        while(cursor.moveToNext()){
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            int salary = cursor.getInt(3);
            Log.i("SQLite", name + ";" + phone + ";" + salary);
        }

        display();
    }

    public void transactionClick(View v) {
        try{
            // 开启事务
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put("salary", 26000);
            db.update("person", values, "name = ?", new String[]{"孙悟空"});

            // 清空values的内容
            values.clear();
            values.put("salary", 20000);
            db.update("person", values, "name = ?", new String[]{"朱八戒"});

//            int i = 9 / 0;
            // 设置事务执行成功,提交时如果这行代码没有执行过,就会回滚
            db.setTransactionSuccessful();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            // 关闭事务,提交数据
            db.endTransaction();
            display();
        }
    }
}

源程序下载

参考:

posted on 2016-05-31 01:10  新思想  阅读(386)  评论(0)    收藏  举报

导航