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

  • 相关阅读:
    Android布局与事件
    android 开发中共享全局数据Application的类
    从Android界面开发谈起【转】
    HttpClient java
    关于整合S&K框架的一些个小注意
    批处理执行多条语句
    Atitit. 软件设计 模式 变量 方法 命名最佳实践 vp820 attilax总结命名表大全
    atitit.软件设计模式大的总结attialx总结
    Atitit.软件开发的最终的设计 dsl化,ast化(建立ast, 解析执行ast)
    atitit。流程图的设计与制作 attilax 总结
  • 原文地址:https://www.cnblogs.com/tangZH/p/5880068.html
Copyright © 2011-2022 走看看