SQLiteOpenHelper类

SQLiteOpenHelper是管理数据库的工具类。

下面提供一个模板:

package com.example.intelligencecontrol.utils;

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

public class MyDBOpenHelper extends SQLiteOpenHelper
{
  public MyDBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory paramCursorFactory, int version)
  {
    super(context, name,null, version);
  }

  public void onCreate(SQLiteDatabase db) //初次使用软件时生成数据库表
  {
    db.execSQL("CREATE TABLE"
            + " control(_id int auto_increment primary key, cname VARCHAR(20), ccommand VARCHAR(20), ccalendar VARCHAR(20))");
  }

  /**
   * 升级软件时更新数据库表结构
   */
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) //newVersion新版本号为代码控制
  {
    db.execSQL("CREATE TABLE control(_id int auto_increment primary key ,cname VARCHAR(20), ccommand VARCHAR(20), ccalendar VARCHAR(20))");
  }
//_id int auto_increment primary key设置id自增长 }

获取SQLiteOpenHelper对象并且操作数据库

 

private MyDBOpenHelper myDBOpenHelper;
private SQLiteDatabase db;
.
.
.
myDBOpenHelper = new MyDBOpenHelper(this, "control.db", null, 1);
db = myDBOpenHelper.getWritableDatabase(); 
Cursor cursor = db.rawQuery("select * from control", null); while (cursor.moveToNext()) //获取数据库的信息 { TimerTaskItem taskItem = new TimerTaskItem(); taskItem.setName(cursor.getString(1)); taskItem.setCommand(cursor.getString(2)); taskItem.setCommandTime(cursor.getString(3)); item.add(taskItem); } . . . //插入数据库 db.execSQL("insert into control values(null,?,?,?)", new String[] { itemData.getName(), itemData.getCommand(),itemData.getCommandTime() }); . . . //删除数据库
db.delete("control", "cname = ? and ccommand = ? and ccalendar = ?",
        new String[] { item.get(position).getName(), item.get(position).getCommand(),
          item.get(position).getCommandTime() });
/** * 关闭数据库 */ @Override public void onDestroy() { super.onDestroy(); if (myDBOpenHelper != null) { myDBOpenHelper.close(); } }

getWritableDatabase()以写的方式打开数据库,若是数据库的磁盘空间满了,那么数据库就只能读不能写,再用它打开数据库就会出错。

若是使用getReadableDatabase()以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,但打开失败后会继续以只读方式打开数据库。

 

转载于:https://www.cnblogs.com/tangZH/p/5880068.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值