GVKun编程网logo

android – 尝试重新打开已经关闭的对象sqlitedatabase(尝试打开的数据库已经被机器 排它方式)

29

在本文中,我们将详细介绍android–尝试重新打开已经关闭的对象sqlitedatabase的各个方面,并为您提供关于尝试打开的数据库已经被机器排它方式的相关解答,同时,我们也将为您带来关于-And

在本文中,我们将详细介绍android – 尝试重新打开已经关闭的对象sqlitedatabase的各个方面,并为您提供关于尝试打开的数据库已经被机器 排它方式的相关解答,同时,我们也将为您带来关于-Android 数据库 SQLiteDatabase 的使用、Android SQLite Database、android SQLiteDatabase、Android SQLiteDatabase 的使用的有用知识。

本文目录一览:

android – 尝试重新打开已经关闭的对象sqlitedatabase(尝试打开的数据库已经被机器 排它方式)

android – 尝试重新打开已经关闭的对象sqlitedatabase(尝试打开的数据库已经被机器 排它方式)

我有一个databaseHandler.我需要计算表中的行数.应用程序因此错误而崩溃:android尝试重新打开已经关闭的对象sqlitedatabase.
我只是在活动中使用此代码:

db.getContactsCount();

但应用程序崩溃了.另外我想重置表(删除表行).我添加了以下方法:

public void deleteTable() {
        sqliteDatabase db = this.getWritableDatabase();
        db.delete("contacts", null, null);
    }

它运作良好,但我不能使用这个:

@Override
public void onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execsql("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

这是databasehandler:

public class DatabaseHandler extends sqliteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(sqliteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execsql(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execsql("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    sqliteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
    sqliteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.movetoFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}

// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    sqliteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.movetoFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.movetoNext());
    }

    // return contact list
    return contactList;
}

// Updating single contact
public int updateContact(Contact contact) {
    sqliteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());

    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact
public void deleteContact(Contact contact) {
    sqliteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}


// Getting contacts Count
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    sqliteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

public void Upgrade (sqliteDatabase db, int oldVersion, int newVersion) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execsql(CREATE_CONTACTS_TABLE);
}

// Deleting single contact
    public void deleteTable() {
        sqliteDatabase db = this.getWritableDatabase();
        db.delete("contacts", null, null);
    }
}

解决方法:

它发生的原因是:

db.close();

在方法中:

void addContact(联系联系人)

public void deleteContact(联系方式)

您不应该关闭与底层数据库的连接,除非您真的不打算再使用它.
使用sqliteOpenHelper:关闭,当你完成你的工作.

此外,对getReadableDatabase()和getWriteableDatabase()的调用99%一次返回相同的数据库对象,并且它们不会重新初始化您手动关闭的数据库连接.

不要被这些方法名称所迷惑.

-Android 数据库 SQLiteDatabase 的使用

-Android 数据库 SQLiteDatabase 的使用

高春辉、王春生、朱峰:关于开源创业的 15 件小事

Android 提供了三种数据存储方式:
第一种是文件存储。
第二种是 SharedPreferences 存储。
第三种是数据库 SQLiteDatabase 存储。

文件存储我就不多说了,而 SharedPreferences 可以存取简单的数据 (int,double,float.etc),它经常用于数据缓存,因为它读取存储简单。详细可以参见本系列《Android 高手进阶教程》7.Android Preferences 的使用

今天我们将讲一下 Android SQLiteDatabase 的使用。而掌握 SqliteDatabase,将会我们接下来掌握 ContentProvider 打下良好的基石。

为了让大家更好的掌握,我们手把手完成该节的 Demo。

第一步:新建一个 Android 工程,命名为 SQLiteDatabaseDemo

SQLiteDatabaseDemo

第二步:创建一个新的类 BooksDB.java 这个类要继承于 android.database.sqlite.SQLiteOpenHelper 抽象类,我们要实现其中两个方法:onCreate (),onUpdate。具体代码如下:

package com.android.tutor;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class BooksDB extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "BOOKS.db";
private final static int DATABASE_VERSION = 1;
private final static String TABLE_NAME = "books_table";
public final static String BOOK_ID = "book_id";
public final static String BOOK_NAME = "book_name";
public final static String BOOK_AUTHOR = "book_author";
 
public BooksDB(Context context) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
 
// 创建 table
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME + " (" + BOOK_ID
+ " INTEGER primary key autoincrement, " + BOOK_NAME
+ " text, " + BOOK_AUTHOR + " text);";
db.execSQL(sql);
}
 
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
 
public Cursor select() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
return cursor;
}
 
// 增加操作
public long insert(String bookname, String author) {
SQLiteDatabase db = this.getWritableDatabase();
/* ContentValues */
ContentValues cv = new ContentValues();
cv.put(BOOK_NAME, bookname);
cv.put(BOOK_AUTHOR, author);
long row = db.insert(TABLE_NAME, null, cv);
return row;
}
 
// 删除操作
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
String where = BOOK_ID + " = ?";
String[] whereValue = { Integer.toString(id) };
db.delete(TABLE_NAME, where, whereValue);
}
 
// 修改操作
public void update(int id, String bookname, String author) {
SQLiteDatabase db = this.getWritableDatabase();
String where = BOOK_ID + " = ?";
String[] whereValue = { Integer.toString(id) };
 
ContentValues cv = new ContentValues();
cv.put(BOOK_NAME, bookname);
cv.put(BOOK_AUTHOR, author);
db.update(TABLE_NAME, cv, where, whereValue);
}
}

第三步:修改 main.xml 布局如下,由两个 EditText 和一个 ListView 组成,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/bookname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/author"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="@+id/bookslist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

第四步:修改 SQLiteDatabaseDemo.java 代码如下:

package com.android.tutor;
 
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
public class SQLiteDatabaseDemo extends Activity implements
AdapterView.OnItemClickListener {
private BooksDB mBooksDB;
private Cursor mCursor;
private EditText BookName;
private EditText BookAuthor;
private ListView BooksList;
 
private int BOOK_ID = 0;
protected final static int MENU_ADD = Menu.FIRST;
protected final static int MENU_DELETE = Menu.FIRST + 1;
protected final static int MENU_UPDATE = Menu.FIRST + 2;
 
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpViews();
}
 
public void setUpViews() {
mBooksDB = new BooksDB(this);
mCursor = mBooksDB.select();
 
BookName = (EditText) findViewById(R.id.bookname);
BookAuthor = (EditText) findViewById(R.id.author);
BooksList = (ListView) findViewById(R.id.bookslist);
 
BooksList.setAdapter(new BooksListAdapter(this, mCursor));
BooksList.setOnItemClickListener(this);
}
 
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
 
menu.add(Menu.NONE, MENU_ADD, 0, "ADD");
menu.add(Menu.NONE, MENU_DELETE, 0, "DELETE");
menu.add(Menu.NONE, MENU_DELETE, 0, "UPDATE");
return true;
}
 
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD:
add();
break;
case MENU_DELETE:
delete();
break;
case MENU_UPDATE:
update();
break;
}
return true;
}
 
public void add() {
String bookname = BookName.getText().toString();
String author = BookAuthor.getText().toString();
// 书名和作者都不能为空,或者退出
if (bookname.equals("") || author.equals("")) {
return;
}
mBooksDB.insert(bookname, author);
mCursor.requery();
BooksList.invalidateViews();
BookName.setText("");
BookAuthor.setText("");
Toast.makeText(this, "Add Successed!", Toast.LENGTH_SHORT).show();
}
 
public void delete() {
if (BOOK_ID == 0) {
return;
}
mBooksDB.delete(BOOK_ID);
mCursor.requery();
BooksList.invalidateViews();
BookName.setText("");
BookAuthor.setText("");
Toast.makeText(this, "Delete Successed!", Toast.LENGTH_SHORT).show();
}
 
public void update() {
String bookname = BookName.getText().toString();
String author = BookAuthor.getText().toString();
// 书名和作者都不能为空,或者退出
if (bookname.equals("") || author.equals("")) {
return;
}
mBooksDB.update(BOOK_ID, bookname, author);
mCursor.requery();
BooksList.invalidateViews();
BookName.setText("");
BookAuthor.setText("");
Toast.makeText(this, "Update Successed!", Toast.LENGTH_SHORT).show();
}
 
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
 
mCursor.moveToPosition(position);
BOOK_ID = mCursor.getInt(0);
BookName.setText(mCursor.getString(1));
BookAuthor.setText(mCursor.getString(2));
 
}
 
public class BooksListAdapter extends BaseAdapter {
private Context mContext;
private Cursor mCursor;
 
public BooksListAdapter(Context context, Cursor cursor) {
 
mContext = context;
mCursor = cursor;
}
 
@Override
public int getCount() {
return mCursor.getCount();
}
 
@Override
public Object getItem(int position) {
return null;
}
 
@Override
public long getItemId(int position) {
return 0;
}
 
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView mTextView = new TextView(mContext);
mCursor.moveToPosition(position);
mTextView.setText(mCursor.getString(1) + "___"
+ mCursor.getString(2));
return mTextView;
}
 
}
}

第五步:运行程序效果如下:

程序效果1

程序效果2

程序效果3

程序效果4

程序效果5

程序效果6

第六步:查看我们所建的数据库。有两种方法:第一种用命令查看:adb shell ls data/data/com.android.tutor/databases。

另一种方法是用 DDMS 查看,在 data/data 下面对应的应用程序的包名 下会有如下数据库,如图所示:

File Explorer


Android SQLite Database

Android SQLite Database

Create

public void insertAnimal(HashMap<StringString> queryValues) {
  SQLiteDatabase database = this.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put("animalName", queryValues.get("animalName"));
  database.insert("animals"null, values);
  database.close();
}

Read

public HashMap<StringString> getAnimalInfo(String id) {
  HashMap<StringString> wordList = new HashMap<StringString>();
  SQLiteDatabase database = this.getReadableDatabase();
  String selectQuery = "SELECT * FROM animals where animalId=''"+id+"''";
  Cursor cursor = database.rawQuery(selectQuery, null);
  if (cursor.moveToFirst()) {
    do {
      wordList.put("animalName", cursor.getString(1));
    } while (cursor.moveToNext());
  }           
  return wordList;
}

Update

public int updateAnimal(HashMap<String, String> queryValues) {
  SQLiteDatabase database = this.getWritableDatabase();  
  ContentValues values = new ContentValues();
  values.put("animalName", queryValues.get("animalName"));
  return database.update("animals", values, "animalId" + " = ?"new String[] { queryValues.get("animalId") });
}

Delete

public void deleteAnimal(String id) {
  Log.d(LOGCAT,"delete");
  SQLiteDatabase database = this.getWritableDatabase();  
  String deleteQuery = "DELETE FROM  animals where animalId=''"+ id +"''";
  Log.d("query",deleteQuery);   
  database.execSQL(deleteQuery);
}

DBController.java

Complete code is as follows,

import java.util.ArrayList;
import java.util.HashMap;
 
import android.util.Log;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class DBController  extends SQLiteOpenHelper {
  private static final String LOGCAT = null;
 
  public DBController(Context applicationcontext) {
    super(applicationcontext, "androidsqlite.db"null1);
    Log.d(LOGCAT,"Created");
  }
 
  @Override
  public void onCreate(SQLiteDatabase database) {
    String query;
    query = "CREATE TABLE animals ( animalId INTEGER PRIMARY KEY, animalName TEXT)";
    database.execSQL(query);
    Log.d(LOGCAT,"animals Created");
  }
  @Override
  public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
    String query;
    query = "DROP TABLE IF EXISTS animals";
    database.execSQL(query);
    onCreate(database);
  }
 
  public void insertAnimal(HashMap<StringString> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("animalName", queryValues.get("animalName"));
    database.insert("animals"null, values);
    database.close();
  }
 
  public int updateAnimal(HashMap<StringString> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();  
    ContentValues values = new ContentValues();
    values.put("animalName", queryValues.get("animalName"));
    return database.update("animals", values, "animalId" + " = ?"new String[] { queryValues.get("animalId") });
  }
 
  public void deleteAnimal(String id) {
    Log.d(LOGCAT,"delete");
    SQLiteDatabase database = this.getWritableDatabase();  
    String deleteQuery = "DELETE FROM  animals where animalId=''"+ id +"''";
    Log.d("query",deleteQuery);   
    database.execSQL(deleteQuery);
  }
 
  public ArrayList<HashMap<StringString>> getAllAnimals() {
    ArrayList<HashMap<StringString>> wordList;
    wordList = new ArrayList<HashMap<StringString>>();
    String selectQuery = "SELECT  * FROM animals";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
      do {
        HashMap<StringString> map = new HashMap<StringString>();
        map.put("animalId", cursor.getString(0));
        map.put("animalName", cursor.getString(1));
        wordList.add(map);
      } while (cursor.moveToNext());
    }
    return wordList;
  }
 
  public HashMap<StringString> getAnimalInfo(String id) {
    HashMap<StringString> wordList = new HashMap<StringString>();
    SQLiteDatabase database = this.getReadableDatabase();
    String selectQuery = "SELECT * FROM animals where animalId=''"+id+"''";
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
      do {
        wordList.put("animalName", cursor.getString(1));
      } while (cursor.moveToNext());
    }           
    return wordList;
  } 
}

布局自己看着弄吧!

android SQLiteDatabase

android SQLiteDatabase

转载地址: http://blog.sina.com.cn/s/blog_6fff321b0100onw8.html

SQLiteDatabase

[功能]

SQLiteDatabase 是关于数据库操作的 可用于 insert delete update query 等操作可惜美中不足的是:

1. 其不支持创建数据库

2. 其不支持版本更新 或者说其不知道如何做 因为具体数据的差异

鉴于以上的缺陷 有一个辅助类可以完成上面功能 那就是:SQLiteOpenHelper

[代码]

1. 定义 SQLiteOpenHelper 并完成 创建 更新 功能

  1. publicclassDBHelper extendsSQLiteOpenHelper { 
  2. publicstaticfinalString TB_NAME = "mycountry"
  3. publicstaticfinalString ID = "_id"
  4. publicstaticfinalString COUNTRY = "country"
  5. publicstaticfinalString CODE = "code"
  6. publicDBHelper(Context context, String name, 
  7. CursorFactory factory,intversion) { 
  8. super(context, name, factory, version); 
  9. publicvoidonCreate(SQLiteDatabase db) { 
  10. db.execSQL("CREATE TABLE IF NOT EXISTS "
  11. + TB_NAME + " ("
  12. + ID + " INTEGER PRIMARY KEY,"
  13. + COUNTRY + " VARCHAR,"
  14. + CODE + " INTEGER)"); 
  15. publicvoidonUpgrade(SQLiteDatabase db, 
  16. intoldVersion, intnewVersion) { 
  17. //TODO 删除数据库之前 做数据备份
  18. db.execSQL("DROP TABLE IF EXISTS "+TB_NAME); 
  19. onCreate(db); 

2. 从 SQLiteOpenHelper 得到 SQLiteDatabase 的实例

  1. DBHelper helper = newDBHelper(this, DB_NAME, null, VERSION); 
  2. SQLiteDatabase db = helper.getWritableDatabase(); 

3. SQLiteDatabase 的一些操作:

* 插入数据:

  1. ContentValues values = newContentValues(); 
  2. values.put(DBHelper.COUNTRY, "中国"); 
  3. values.put(DBHelper.CODE, 86); 
  4. db.insert(DBHelper.TB_NAME,DBHelper.ID, values); 

* 改动数据

  1. db.insert(DBHelper.TB_NAME,DBHelper.ID,null); 
  2. values.clear(); 
  3. values.put(DBHelper.COUNTRY, "意大利"); 
  4. values.put(DBHelper.CODE, 39); 
  5. db.update(DBHelper.TB_NAME, values,DBHelper.ID + " = 2",null); 

* execSQL 执行 SQL 语言

  1. db.execSQL("INSERT INTO "
  2. + DBHelper.TB_NAME + "("
  3. + DBHelper.COUNTRY + ","
  4. + DBHelper.CODE + ") VALUES "
  5. "('' 洪都拉斯 '',504)"); 

* 查询数据

  1. Cursor c = db.query(DBHelper.TB_NAME,null,null,null,null,null
  2. DBHelper.CODE+" DESC"); 

* 删除数据所有数据

  1. db.delete(DBHelper.TB_NAME,null,null); 

数据库的生成 调用 getWiterAbleDatabase getReadAbleDatabase 生成数据库 i

android 嵌入式数据库 为单用户数据库 所以 可以不调用 db.close () 来关闭数据库这样反而可以提高性能

Android SQLiteDatabase 的使用

Android SQLiteDatabase 的使用

Java 代码 
  1. package com.shawn.test;  
  2. import android.content.ContentValues;  
  3. import android.content.Context;  
  4. import android.database.Cursor;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7. import android.util.Log;  
  8. publicclass DatabaseAdapter{  
  9. privatestaticfinal String DB_NAME = "Test.db";    // 数据库名
  10. privatestaticfinalint    DB_VERSION = 1;         // 数据库版本
  11. privatestaticfinal String DB_TABLE = "my_order";  // 表名
  12. privatestaticfinal String KEY_ID = "_id";         //id
  13. privatestaticfinal String KEY_ORDER_ID = "order_id";  // 订单号
  14. privatestaticfinal String KEY_TYPE = "_type";         // 订单类型
  15. privatestaticfinal String KEY_STATE = "_state";       // 订单状态
  16. private Context context;  
  17. private DatabaseHelper mDatabaseHelper;  
  18. private SQLiteDatabase mSQLiteDatabase;  
  19. privatestaticclass DatabaseHelper extends SQLiteOpenHelper{  
  20. // 创建数据库语句
  21. privatestaticfinal String DB_CREAT = "CREATE TABLE "
  22.                 + DB_TABLE  
  23.                 + " (" + KEY_ID + " INTEGER PRIMARY KEY,"
  24.                 + KEY_ORDER_ID + " TEXT,"
  25.                 + KEY_TYPE + " INTEGER,"
  26.                 + KEY_STATE + " INTEGER)";  
  27. public DatabaseHelper(Context context) {  
  28. super(context, DB_NAME,  null , DB_VERSION);  
  29.         }  
  30. @Override
  31. publicvoid onCreate(SQLiteDatabase db) {  
  32. // TODO Auto-generated method stub
  33.             db.execSQL(DB_CREAT);  
  34.         }  
  35. @Override
  36. publicvoid onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  37. // TODO Auto-generated method stub
  38.             db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);  
  39.             onCreate(db);  
  40.         }  
  41.     }  
  42. public DatabaseAdapter(Context context) {  
  43. this.context = context;  
  44.     }  
  45. // 开启
  46. publicvoid open() {  
  47.         mDatabaseHelper = new DatabaseHelper(context);    
  48.         mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();  
  49.     }  
  50. // 关闭
  51. publicvoid close() {   
  52.         mSQLiteDatabase.close();  
  53.         mDatabaseHelper.close();  
  54.     }  
  55. // 增
  56. publiclong insertData(String orderId, int type) {    
  57.         ContentValues values = new  ContentValues();     
  58.         values.put(KEY_ORDER_ID, orderId);   
  59.         values.put(KEY_TYPE, type);  
  60.         values.put(KEY_STATE, Config.STATE_APPLY);   
  61. long id = mSQLiteDatabase.insert(DB_TABLE, KEY_ID, values);   
  62. return id;  
  63.     }  
  64. // 删
  65. publicboolean deleteData(Context context, long id) {  
  66. boolean delete = mSQLiteDatabase.delete(DB_TABLE, KEY_ID + "=" +id, null)>0;  
  67. return delete;  
  68.     }  
  69. // 改
  70. publicboolean updateData(long id, int state) {  
  71.         ContentValues values = new  ContentValues();    
  72.         values.put(KEY_STATE, ""+state);   
  73. boolean update = mSQLiteDatabase.update(DB_TABLE, values, KEY_ID + "=" +id, null)>0;  
  74. return update;  
  75.     }  
  76. // 查
  77. public Cursor fetchData(String selection) {  
  78.         Cursor mCursor = mSQLiteDatabase.query(DB_TABLE, new String[]{KEY_ID, KEY_ORDER_ID, KEY_TYPE, KEY_STATE}, selection, nullnullnullnull);  
  79. if(mCursor != null)  
  80.             mCursor.moveToFirst();  
  81. return mCursor;  
  82.     }  
  83. }  

我们今天的关于android – 尝试重新打开已经关闭的对象sqlitedatabase尝试打开的数据库已经被机器 排它方式的分享已经告一段落,感谢您的关注,如果您想了解更多关于-Android 数据库 SQLiteDatabase 的使用、Android SQLite Database、android SQLiteDatabase、Android SQLiteDatabase 的使用的相关信息,请在本站查询。

本文标签: