SQLite

  Android系统中集成的是SQLite3版本,SQLite是一个开源的嵌入式数据库,他支持NULL、INTEGER、REAL、TEXT和BLOB数据类型,不支持静态数据类型,而是使用列关系。
  创建访问数据库,必须继承SQLiteOpenHelper类,且必须实现onCreate和onUpgrade两个方法,当创建数据库时,就会调用onCreate,所以可将要添加的table写在里面。当更新数据库时,则会调用onUpgrade,所以可将要更新的table的sql写在里面。前者用于初次使用软件时生成数据库,后者用于升级软件时更新数据库表结构。通过getWritableDatabase()和getReadableDatabase()来获得数据库。
  代码:
package com.kevin.sqlite;

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

public class ToDoDB extends SQLiteOpenHelper {

	private final static String DATABASE_NAME = "todo_db";
	private final static int DATABASE_VERSION = 1;
	private final static String TABLE_NAME = "todo_table";
	public final static String FIELD_ID = "_id";
	public final static String FIELD_TEXT = "todo_text";
	public ToDoDB(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		System.out.println("onCreate");
		// 创建table
		String sql = "create table " + TABLE_NAME + " ( " + FIELD_ID +
		  			 " INTEGER primary key autoincrement, " + FIELD_TEXT + " text)";
		db.execSQL(sql);
		System.out.println("执行完成");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
		System.out.println("onUpgrade");
		String sql = " drop table if exists " + TABLE_NAME;
		db.execSQL(sql);
		onCreate(db);
	}
	
	public Cursor select(){
		System.out.println("select");
		SQLiteDatabase db = this.getReadableDatabase();
		/*
		 * 参数说明:第一个参数表名
		 * 第二个参数要查询的列名,如果填null,则表示所有列
		 * 第三个参数查询条件
		 * 第四个参数查询条件的值
		 * 第五个groupby语句
		 * 第六个having语句
		 * 第七个orderby语句
		 */
		Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
		return cursor;
	}
	
	public long insert(String  text){
		System.out.println("insert");
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(FIELD_TEXT, text);
		/*
		 * 第一个参数表名
		 * 第二个参数插入列不能为空的列名
		 * 第三个参数ContentVlaues对象
		 */
		long row = db.insert(TABLE_NAME, null, cv);
		return row;
	}
	
	public void delete(int id){
		System.out.println("");
		SQLiteDatabase db = this.getWritableDatabase();
		String where = FIELD_ID + " = ? ";
		String[] whereValue = {Integer.toString(id)};
		db.delete(TABLE_NAME, where, whereValue);
	}
	
	public void update(int id, String text){
		System.out.println("update");
		SQLiteDatabase db = getWritableDatabase();
		String where = FIELD_ID + " = ? ";
		String[] whereValue = {Integer.toString(id)};
		ContentValues cv = new ContentValues();
		cv.put(FIELD_TEXT, text);
		db.update(TABLE_NAME, cv, where, whereValue);
	}

}

你可能感兴趣的:(android)