• 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()以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,但打开失败后会继续以只读方式打开数据库。

  • 相关阅读:
    前端请求跨域理解
    可视化交互行为
    文章标题
    在map上标记point
    基于force布局的map
    stack布局
    python一些特有语法
    histogram布局用法
    patition布局
    Shell命令行处理JSON
  • 原文地址:https://www.cnblogs.com/tangZH/p/5880068.html
Copyright © 2020-2023  润新知