«

Android中SQLite数据库的使用

时间:2024-3-2 17:17     作者:韩俊     分类: Android


SQLite是轻量级的、嵌入式的、关系型数据库,SQLite可移植性好,很容易使用,很小,高效而且可靠。在Android中保存大量数据需要使用到SQLite数据库,下面就介绍一下SQLite常用操作方法的简单实例。
首先创建数据库和表代码如下:

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

public class SQLite extends SQLiteOpenHelper {

    public SQLite(Context context) {
        //必须通过super调用父类当中的构造函数
        super(context, "user.db", null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String str = "create table person(id integer primary key autoincrement,name varchar(20),password varchar(20))";
        db.execSQL(str);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

然后实现数据的增删改查方法,实现方式有两种:
(1)使用SQL语句实现,代码如下:

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

import com.studyone.db.SQLite;

public class PersonDao {
    private SQLite sqlite;
    //在构造放法中创建一个SQLite对象   
    public PersonDao( Context context){
        sqlite = new SQLite(context);
    }

    public void insert(String name,String password){
        SQLiteDatabase db = sqlite.getWritableDatabase();
        //只有调用了DatabaseHelper对象的getReadableDatabase()方法,或者是getWritableDatabase()方法之后,才会创建或打开一个数据库        
        db.execSQL("insert into person (name,password) values (?,?)",new Object[]{name,password});
        db.close();
    }

    public String find(String name){
        String result="";
        SQLiteDatabase db = sqlite.getReadableDatabase();
        Cursor curse = db.rawQuery("select name,password from person where name=?", new String[]{name});
        while( curse.moveToNext() ){
            result += curse.getString(curse.getColumnIndex("name"));
            result += curse.getString(curse.getColumnIndex("password"));
        }
        curse.close();
        db.close();
        return result;
    }

    public void update(String name ,String password){
        SQLiteDatabase db = sqlite.getWritableDatabase();
         //execSQL函数用于执行SQL语句  
        db.execSQL("update person set password = ? where name=?",new String[]{password,name});
        db.close();
    }

    public void delete(String name){
        SQLiteDatabase db = sqlite.getWritableDatabase();
        db.execSQL("delete from person where name=?",new String[]{name});
        db.close();
    }

}

(2)调用系统api实现,代码如下:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.studyone.db.SQLite;

public class PersonDao {
    private SQLite sqlite;

    public PersonDao( Context context){
        sqlite = new SQLite(context);
    }

    public void insert(String name,String password){
        SQLiteDatabase db = sqlite.getWritableDatabase();

        ContentValues values = new ContentValues();//生成ContentValues对象   
        values.put("name", name);
        values.put("password", password);
        db.insert("person", null, values);
        db.close();
    }

    public String find(String name){
        String result="";
        SQLiteDatabase db = sqlite.getReadableDatabase();
        Cursor curse = db.query("table", new String[]{"name","password"}, "name=?",  new String[]{name}, null, null, null);
        while( curse.moveToNext() ){
            result += curse.getString(curse.getColumnIndex("name"));
            result += curse.getString(curse.getColumnIndex("password"));
        }
        curse.close();
        db.close();
        return result;
    }

    public void update(String name ,String password){
        SQLiteDatabase db = sqlite.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("password", password);
        db.update("person", values, "name=?", new String[]{name});
        db.close();
    }

    public void delete(String name){
        SQLiteDatabase db = sqlite.getWritableDatabase();
        db.delete("person", "name=?", new String[]{name});
        db.close();
    }

}

然后就可以调用实现的方法操作数据了

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {

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

    public void updateBtn(View v) throws Exception {
        new PersonDao(this).update("554849416", "654321");
        Toast.makeText(MainActivity.this,
                "update ok", Toast.LENGTH_LONG)
                .show();
    }

    public void findBtn(View v) throws Exception {
        Toast.makeText(MainActivity.this,
                new PersonDao(this).find("554849416"), Toast.LENGTH_LONG)
                .show();
    }

    public void insertBtn(View v) throws Exception {
        new PersonDao(this).insert("554849416", "123456");
        Toast.makeText(MainActivity.this, "insert ok", Toast.LENGTH_LONG)
                .show();

    }

    public void deleteBtn(View v) throws Exception {
        new PersonDao(this).delete("554849416");
        Toast.makeText(MainActivity.this, "delete ok", Toast.LENGTH_LONG)
                .show();

    }

}

布局文件代码

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/insertbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="insert" 
        android:onClick="insertBtn"
        />
    <Button
        android:id="@+id/findbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/insertbtn"
        android:text="find" 
        android:onClick="findBtn"
        />
    <Button
        android:id="@+id/updatebtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/findbtn"
        android:text="update" 
        android:onClick="updateBtn"
        />
     <Button
        android:id="@+id/deletebtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/updatebtn"
        android:text="delete" 
        android:onClick="deleteBtn"
        />

</RelativeLayout>

OK搞定。

标签: android

热门推荐