首页 > 代码库 > 【.NET老猿学安卓系列】数据库读写
【.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();
【.NET老猿学安卓系列】数据库读写
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。