android sqlite 简单使用(实例)

来源:互联网 发布:linux命令ls -lre意思 编辑:程序博客网 时间:2024/05/29 19:15
package api;import android.content.ContentValues;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.Cursor;import android.util.Log;import java.util.ArrayList;import java.util.List;/** * Created by Juxuny on 14-4-29. */public class DBManager {    private Context context;    private String dbName;    private String userInfoTableName = "userInfo";    private SQLiteDatabase sqLiteDatabase;    //后面openOrCreateDatabase函数在context中,这里就要把context传过来    public DBManager(Context context, String dbName) {        this.context = context;        this.dbName = dbName;        sqLiteDatabase = context.openOrCreateDatabase(dbName, Context.MODE_PRIVATE,null);        try {            //执行sql语句创建数据表,三个字段分别是_id, userName,password            sqLiteDatabase.execSQL("CREATE TABLE " + userInfoTableName +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, userName VARCHAR, password VARCHAR)");        } catch (Exception e) {            e.printStackTrace();        }    }    public void insertUserInfo(UserInfo userInfo) {        ContentValues contentValues = new ContentValues();        contentValues.put("userName", userInfo.userName);        contentValues.put("password", userInfo.password);        sqLiteDatabase.insert(userInfoTableName,null, contentValues);    }    public List<UserInfo> findUserInfo() {        List<UserInfo> result = new ArrayList<UserInfo>();        Cursor cursor = sqLiteDatabase.rawQuery("select * from userInfo",null);        while(cursor.moveToNext()) {            result.add(new UserInfo(cursor.getString(1), cursor.getString(2)));//上面create table 时,创建了3个字段,就分别对应0,1,2,getString(0)就返回_id,getString(1)返回userName,getString(2)返回password;            Log.d("test",cursor.getString(1));            Log.d("test",cursor.getString(2));        }        return result;    }    //根据userName更新password    public void updateUserInfo(String userName, String password){        //用sql语句更新数据库        sqLiteDatabase.execSQL(String.format("update %s set password=\"%s\" where userName=\"%s\"", userInfoTableName, password,userName));    }}

0 0
原创粉丝点击