第一步:继承SQLiteOpenHelper
package cn.edu.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class MySqliteHelper extends SQLiteOpenHelper{ public MySqliteHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version);//factory是null,表示使用CursorFactory是系统自带的 // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase arg0) { //数据库在每一次创建的时候被调用的 // TODO Auto-generated method stub arg0.execSQL("create table product(id integer primary key autoincrement,name varchar(20),time varchar(20))");//当数据库已经存在在手机上的时候,这个方法SQL语句不会被执行 } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { //当构造方法中的version和以前的数字不一样的时候会调用该方法 // TODO Auto-generated method stub //该函数是给数据库升级的时候调用的 arg0.execSQL("alter table product add categoryid"); } }
二、数据库的增删改查
package cn.edu.service; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import cn.edu.database.MySqliteHelper; public class ProductService { private Context context; public ProductService(Context context) { this.context=context; } public void save() { MySqliteHelper helper=new MySqliteHelper(context,"test.db",null,1); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("insert into product(name,time) values('12','12')"); db.close(); } public void delete() { MySqliteHelper helper=new MySqliteHelper(context,"test.db",null,1); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("delete product where id=1"); db.close(); } public void findById(Integer id) { MySqliteHelper helper=new MySqliteHelper(context,"test.db",null,1); SQLiteDatabase db=helper.getWritableDatabase(); Cursor cursor=db.rawQuery("select * from product where id=?", new String[] {id.toString()}); if(cursor.moveToFirst()) { System.out.println(cursor.getInt(cursor.getColumnIndex("id"))); System.out.println(cursor.getInt(cursor.getColumnIndex("name"))); System.out.println(cursor.getInt(cursor.getColumnIndex("time"))); } } public void update() { MySqliteHelper helper=new MySqliteHelper(context,"test.db",null,1); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("update product set name='何' where id=1"); db.close(); } public void transaction() { MySqliteHelper helper=new MySqliteHelper(context,"test.db",null,1); SQLiteDatabase db =helper.getWritableDatabase(); db.beginTransaction(); try{ db.execSQL(""); db.execSQL(""); db.setTransactionSuccessful();//设置数万的标志为true } finally{ db.endTransaction(); } } }