【.NET老猿学安卓系列】数据库读写

第一步,就是下面这个类:


package
com.fengzili.dbTesting; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; //看好这个明明空间 import android.util.Log; /** * Created by Administrator on 2014/11/4. */ public class PersonHelper extends SQLiteOpenHelper{ public PersonHelper(Context context){ super(context,"person.db",null,1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL("create table person(id integer primary key,name nvarchar(20),number nvarchar(20))"); //初始化数据库结构 } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) { Log.e("fengzili","数据库从"+i+"升级到了"+i2); } }
//简单版的增删改查

package com.com.fengzili.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.fengzili.dbTesting.PersonHelper;

/**
 * Created by Administrator on 2014/11/4.主要学习下如何用现成的系统函数简化SQL语句编写,当然熟练以后还是写sQL比较直观,封装的话说也没传说中那么美好
 */
public class PersonDao {

    private PersonHelper helper;

    public void InsertNewRecord(String name,String number)
    {
        SQLiteDatabase sld= this.getHelper().getWritableDatabase();
        sld.execSQL("insert into person(name,number) values (?,?)",new Object[]{"冯","132"});
        ContentValues cvs=new ContentValues(4);
        cvs.put("name",name);
        cvs.put("number",number);
        sld.insert("Person","id",cvs);
        sld.close();
    }

    public  void Update(String name,String newNumber)
    {
        SQLiteDatabase db=this.getHelper().getWritableDatabase();
        ContentValues cvs=new ContentValues(4);
        cvs.put("number",newNumber);
        db.update("person",cvs,"name=?",new String[]{name});
        db.close();
    }

    public void  ReadAll()
    {
        SQLiteDatabase db=this.getHelper().getReadableDatabase();
        Cursor cur= db.query(false, "person", null, "id>?", new String[]{"0"}, null, null, null, "10");
        while (cur.moveToNext())
        {
            Log.e("FengZiLi","PersonName:"+cur.getString(cur.getColumnIndex("name"))+"      number:"+cur.getString(cur.getColumnIndex("number")));
        }
    }

    public void Delete(String name)
    {

    }

    public PersonHelper getHelper() {
        return helper;
    }

    public void setHelper(PersonHelper helper) {
        this.helper = helper;
    }
}

代码的使用:

 PersonDao psd=new PersonDao();
                psd.setHelper(new PersonHelper(MyActivity.this));
                psd.InsertNewRecord("张三丰","885");
                psd.Update("张三丰","998");
                psd.ReadAll();

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。