SQLite 是一款轻量级的关系型数据库, 它的运算速度非常快,占用资源很少。存储大量复杂的关系型数据的时候使用。
一、创建数据库
SQLiteOpenHelper 帮助类, 借助这个类就可以非常简单地对数据库进行创建和升级。 SQLiteOpenHelper 中有两个抽象方法,分别是onCreate()和 onUpgrade(),我们必须在自己的帮助类里面重写这两个方法,然后分别在这两个方法中去实现创建、升级数据库的逻辑。getReadableDatabase() 和getWritableDatabase()。 这两个方法都可以创建或打开一个现有的数据库(如果数据库已存在则直接打开,否则创建一个新的数据库),并返回一个可对数据库进行读写操作的对象。数据库文件会存放在/data/data/<package name>/databases/目录下。
新建一个 DatabaseTest 项目。新建 MyDatabaseHelper类继承自 SQLiteOpenHelper。
package com.example.databasetest; import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK="create table book (" + "id integer primary key autoincrement, " + "author text, " + "price real, " + "pages integer, " + "name text)"; public static final String CREATE_CATEGORY = "create table Category (" + "id integer primary key autoincrement, " + "category_name text, " + "category_code integer)"; private Context mContext; public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub mContext=context; } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_BOOK); db.execSQL(CREATE_CATEGORY); Toast.makeText(mContext,"Create succeeded", Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("drop table if exists Book"); db.execSQL("drop table if exists Category"); onCreate(db); } }
package com.example.databasetest; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper= new MyDatabaseHelper(this, "BookStore.db", null, 2); Button createDatabase =(Button)findViewById(R.id.create_database); Button addData =(Button)findViewById(R.id.add_data); Button upDateData=(Button)findViewById(R.id.update_data); Button deleteButton = (Button) findViewById(R.id.delete_data); Button queryButton = (Button) findViewById(R.id.query_data); queryButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query("Book", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { // 遍历Cursor对象,取出数据并打印 String name = cursor.getString(cursor.getColumnIndex("name")); String author = cursor.getString(cursor.getColumnIndex("author")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); double price = cursor.getDouble(cursor.getColumnIndex("price")); Log.d("MainActivity", "book name is " + name); Log.d("MainActivity", "book author is " + author); Log.d("MainActivity", "book pages is " + pages); Log.d("MainActivity", "book price is " + price); } while (cursor.moveToNext()); } cursor.close(); } }); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase db=dbHelper.getWritableDatabase(); db.delete("book", "pages > ?", new String[] { "500" }); } }); upDateData.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("price", 10.99); db.update("book", values, "name=?", new String[]{"The Da Vinci Code"}); } }); addData.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase db = dbHelper.getWritableDatabase();//getWritableDatabase()返回SQLiteDatabase类型 支持CRUD ContentValues values = new ContentValues(); // 开始组装第一条数据 values.put("name", "The Da Vinci Code"); values.put("author", "Dan Brown"); values.put("pages", 454); values.put("price", 16.96); db.insert("book", null, values); values.clear(); // 开始组装第二条数据 values.put("name", "The Lost Symbol"); values.put("author", "Dan Brown"); values.put("pages", 510); values.put("price", 19.95); db.insert("book", null, values); } }); createDatabase.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dbHelper.getWritableDatabase(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }我们在 onCreate()方法中构建了一个 MyDatabaseHelper 对象, 并且通过构造函数的参数将数据库名指定为 BookStore.db,版本号指定为 1,然后在 Create database 按钮的点击事件里调用了 getWritableDatabase()方法。 这样当第一次点击 Create database 按钮时, 就会检测