加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SQLite使用方法 SQLiteOpenHelper操作

发布时间:2020-12-12 20:28:59 所属栏目:百科 来源:网络整理
导读:程序内使用SQLite数据库是通过SQLiteOpenHelper进行操作1. 自己写个类继承SQLiteOpenHelper,重写以下3个方法public void onCreate(SQLiteDatabase db) {//创建数据库时的操作,如建表} public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersi

程序内使用SQLite数据库是通过SQLiteOpenHelper进行操作
1.       自己写个类继承SQLiteOpenHelper,重写以下3个方法
public void onCreate(SQLiteDatabase db) 
{//创建数据库时的操作,如建表}
 
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) 
       {
           //版本更新的操作
       }
2.    通过SQLiteOpenHelper的getWritableDatabase()获得一个SQLiteDatabase数据库,以后的操作都是对SQLiteDatabase进行操作。
3.       对得到的SQLiteDatabase对象进行增,改,删,查等操作。
代码
package cx.myNote;
 
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
//DBOptions for login
public class DBOptions {
       private static final String DB_NAME = "notes.db";
       private static final String DB_CREATE="create table logininf(name text,pwd text)";
       public class DBHelper extends SQLiteOpenHelper
       {
 
              public DBHelper(Context context) {
                     super(context,DB_NAME,null,1);
                     }
 
              @Override
              public void onCreate(SQLiteDatabase db) {
                     // TODO Auto-generated method stub
                     //建表
                 db.execSQL(DB_CREATE);
              }
              
              @Override
              public void onUpgrade(SQLiteDatabase db,int newVersion) {
                     // TODO Auto-generated method stub
                     db.execSQL("drop table if exists logininf");
                     onCreate(db);
              }
              
       }
       private Context context;
       private SQLiteDatabase db;
       private DBHelper dbHelper;
       public  DBOptions(Context context)
       {
              this.context = context;
              dbHelper = new DBHelper(context);
              db=dbHelper.getReadableDatabase();
              
       }
  //自己写的方法,对数据库进行操作
       public String getName()
       {
              
              Cursor cursor = db.rawQuery("select name from logininf",null);
              cursor.moveToFirst();
              return cursor.getString(0);     
       }
       public int changePWD(String oldP,String pwd)
       {
              ContentValues values = new ContentValues();
              values.put("pwd",pwd);
              return db.update("logininf",values,"pwd="+oldP,null);
       }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读