码迷,mamicode.com
首页 > 移动开发 > 详细

android之SQLlite操作

时间:2016-06-16 21:40:16      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

布局文件


创建了四个按键,分别对应增删改查

<?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="xidian.dy.com.chujia.MainActivity">
        <Button
            android:id="@+id/btn_insert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="插入一条数据"/>
        <Button
            android:id="@+id/btn_query"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查询当前数据" />
        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改一条数据"/>
        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除一条数据"/>
</LinearLayout>

数据库操作


package xidian.dy.com.chujia;

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.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private SQLiteDatabase db;
    private MainActivity mContext;
    private int i = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mContext = MainActivity.this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyDBOpenHelper myDBHelper = new MyDBOpenHelper(mContext, "my.db", null, 1);
        db = myDBHelper.getWritableDatabase();
        bindViews();
    }

    private void bindViews() {
        Button btn_insert = (Button) findViewById(R.id.btn_insert);
        Button btn_query = (Button) findViewById(R.id.btn_query);
        Button btn_update = (Button) findViewById(R.id.btn_update);
        Button btn_delete = (Button) findViewById(R.id.btn_delete);
        if(btn_query != null)
            btn_query.setOnClickListener(this);
        if(btn_insert != null)
            btn_insert.setOnClickListener(this);
        if(btn_update != null)
            btn_update.setOnClickListener(this);
        if(btn_delete != null)
            btn_delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_insert:
                ContentValues values1 = new ContentValues();
                //name为数据库中属性名,第二个为欲插入的值
                values1.put("name", "呵呵~" + i);
                i++;
                //参数依次是:表名,强行插入null值得数据列的列名,一行记录的数据
                db.insert("person", null, values1);
                Toast.makeText(mContext, "插入完毕~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_query:
                StringBuilder sb = new StringBuilder();
                //参数依次是:表名,列名,where约束条件,where中占位符提供具体的值,指定group by的列,进一步约束
                //指定查询结果的排序方式
                Cursor cursor = db.query("person", null, null, null, null, null, null);
                if (cursor.moveToFirst()) {
                    do {
                        int id = cursor.getInt(cursor.getColumnIndex("_id"));
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        sb.append("id:" + id + ":" + name + "\n");
                    } while (cursor.moveToNext());
                }
                cursor.close();
                Toast.makeText(mContext, sb.toString(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_update:
                ContentValues values2 = new ContentValues();
                values2.put("name", "嘻嘻~");
                //参数依次是表名,修改后的值,where条件,以及约束,如果不指定三四两个参数,会更改所有行
                db.update("person", values2, "name = ?", new String[]{"呵呵~2"});
                break;
            case R.id.btn_delete:
                //参数依次是表名,where条件,约束
                db.delete("person", "_id = ?", new String[]{"3"});
                //多个条件
//                db.delete("person", "_id=? and name=?", new String[]{"1", "小名"});
                break;
        }
    }
}

这里先创建一个数据库助手,通过该助手获取数据库操作对象。利用该对象提供的API来操作数据库。

数据库助手类


 

package xidian.dy.com.chujia;

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

/**
 * Created by dy on 2016/6/13.
 */
public class MyDBOpenHelper extends SQLiteOpenHelper {
    public MyDBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
                          int version) {super(context, "my.db", null, 1); }
    @Override
    //数据库第一次创建时被调用
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE person(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20))");

    }
    //软件版本号发生改变时调用
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");
    }
}

事务


如果在数据库操作中使用到了事务可以参考以下的代码

    //转账事物
    public void transaction(){
        try {
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put("salary", 9000);
            db.update("person",values,"name=?", new String[]{"小王"});
            values.clear();
            values.put("salary", 11000);
            db.update("person", values, "name=?", new String[]{"小张"});
            //设置事务执行成功
            db.setTransactionSuccessful();
        }finally {
            //关闭事物,同时提交,如果已经设置事务执行成功,那么sql将会生效,否则SQL回滚
            db.endTransaction();
        }
    }

 

android之SQLlite操作

标签:

原文地址:http://www.cnblogs.com/xidongyu/p/5592178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!