Android之Sqlite数据库的使用

1.获取数据库对象。

这就需要SqLiteOpenHelper类了,这是一个抽象类,当需要创建或打开一个数据库并获得数据库对象时,首先创建一个辅助对象。然后调用该对象的getWritableDatabase或getReadable方法获得SQLiteDatabase对象。


2.操作数据。

(1) void execSQL(String sql);

(2) void execSQL(String sql,Object[]  bindArgs);

解释:执行指定的sql语句,不可以为查询语句。不可以传入以";"隔开的多条sql语句。

sql:要执行的sql语句。

bindArgs:将来替换SQL表达式中的"?"的参数列表,目前只支持byte数据,String,long和double类型。


(3) long insert(String table,String nullColumnHack,ContentValues values);

(4)long insertOrThrow(String table,String nullColumnHack,ContentValues values);

解释:向表中插入一行数据,返回插入行的id。方法insertOrThrow会抛出SQLException异常。

table:要操作的表明。

nullColumnHack:如果传入的values参数为null或空时,该参数所指定的列会被赋值为null插入到表中。

values:要插入的数据以“列名-列值”的键值对方式封装到ContentValues对象中。


(5)

int update(String  table,ContentValues  values,String  whereClause,String[]  whereArgs);

解释:向表中更新数据,返回更新的行数。

table:要操作的表明。

values:更新后的“列名-列值”的键值对。

whereClause:指明更新位置的where子句,如果是null则表示更新表中所有行。

whereArgs:将来用于替换whereClause中“?”参数列表。


(6)

int delete(String  table,String  whereClause,String[]  whereArgs);

解释:删除表中满足指定条件的行,返回删除的个数。

table:要操作的表明。

whereClause:指明闪出去位置的where子句,如果传入null,则会删除所有的行。

whereArgs:将来用于替换whereClause中的"?"的参数列表。


检索数据:

(7)

Cursor rawQuery(String sql,String[]  args);

Cursor rawQueryWithFactory(SQLiteDatabase.CursorFactory  factory,String sql,String[] args,String editable);

解释:执行指定的SQL查询语句,返回Cursor对象作为查询结果。

sql:要执行的SQL语句。

args:用于替换SQL查询语句中“?”的参数列表。

factory:构造 Cursor对象时所使用的CursorFactory对象,为null则使用默认值。

editTable:首个可编辑表的名称。


(8)

Cursor query(boolean distinct,String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit);


Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy);


Cursor query(String table,String[] colums,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit);


解释:查询指定的表,返回Cursor对象作为查询结果。

distinct:是否要求每一行具有唯一性,true表示要求。

table:要操作的表名。

columns:指明查询结果中需要返回的列,如果传入null则返回所有列。

selection:对应SQL语句中where子句,指明查询结果需要返回的行数,传入null会返回所有行。

selectionArgs:用于替换selection参数中的“?”的参数列表。

groupBy:对应SQL语句中的group by子句,对查询结果分组,传入null表示不分类。

having;对应SQL语句中的having子句,需要与groupBy参数配合使用,传入null表示不对分组结果附加条件。

orderBy:对应SQL语句中的order by语句,传入null为默认排序。

limit:对应SQL语句中的limit语句,对查询返回的行数进行限制,传入null表示不作限制。



测试代码:

MySqliteOpenHelper.java:

package zy.just.com.sqlitedemo;

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

/**
 * Created by print on 2016/3/15.
 */
public class MySqliteOpenHelper extends SQLiteOpenHelper {


    public MySqliteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }


    @Override//数据库创建时调用
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table if not exists hero_info(id integer primary key autoincrement,name varchar,level integer)");//创建表
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


MainActivity.java:

package zy.just.com.sqlitedemo;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private MySqliteOpenHelper myHelper;// 数据库辅助类对象的引用
    private TextView tv;//TextView对象的引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        myHelper = new MySqliteOpenHelper(this,"my.db",null,1);// 创建MySQLiteOpenHelper辅助类对象
        insertAndUpdateData(myHelper); // 向数据库中插入和更新数据
        String s = queryData(myHelper);// 向数据库中查询数据
        tv.setText("名字\t等级\n" + s); // 将查询到的数据显示到屏幕上
    }

    /**
     *  向数据库中插入和更新数据
     * @param myHelper
     */
    private void insertAndUpdateData(MySqliteOpenHelper myHelper) {

        SQLiteDatabase database = myHelper.getWritableDatabase();// 获取数据库对象
        // 使用execSQL方法向表中插入数据
        database.execSQL("insert into hero_info(name,level) values('Hero1',1)");
        // 使用insert方法向表中插入数据
        ContentValues values = new ContentValues();// 创建ContentValues对象存储列名-列值映射
        values.put("name","hero2");
        values.put("level", 2);
        database.insert("hero_info", null, values); // 调用方法插入数据
        // 使用update方法更新表中的数据
        values.clear();//清空ContentValues对象
        values.put("name", "hero2");
        values.put("level", 3);
        database.update("hero_info", values, "level=?", new String[]{"2"}); // 更新表中level2的那行数据
        database.close();// 关闭SQLiteDatabase对象
    }

    /**
     * 方法:从数据库中查询数据
     */
    public String queryData(MySqliteOpenHelper myHelper){
        String result = "";
        SQLiteDatabase db = myHelper.getWritableDatabase();// 获得数据库对象
        Cursor cursor = db.query("hero_info",null, null, null, null, null,"id asc");//asc表示升序,查询表中数据
        int nameIndex = cursor.getColumnIndex("name");// 获取name列的索引
        int levelIndex = cursor.getColumnIndex("level");// 获取level列的索引
        while(cursor.moveToNext()){
            result = result + cursor.getString(nameIndex)+" ";
            result = result + cursor.getInt(levelIndex)+" \n";
        }
        cursor.close();// 关闭结果集
        db.close(); // 关闭数据库对象
        return result;
    }

}
布局文件:

<RelativeLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

运行结果:


猜你喜欢

转载自blog.csdn.net/zhangying1994/article/details/50900934