数据库
-
第一步
创建一个新工程,创建一个class这个class继承于SQLiteOpenHelper这个类,并实现两个方法和一个构造方法 -
第二步:调用SQLiteOpenHelper这个类的构造方法,先创建一个对象,然后调用创建数据库的方法 参数1:许你一个上下文 参数2:数据库名称 参数3:null 参数四:不能小于1;
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();//如果数据库不存在,先创建数据库 ,获取一个可读可写数据库对象 -
第三步:创建数据库表
@Override
public void onCreate(SQLiteDatabase arg0) {
//创建数据库表
arg0.execSQL("create table person(_id integer primary key autoincrement, name char(10),salary char(20),phone integer(20) )");
} -
第四步:创建表之后就可以进行表的增删改查了
public void insert(){
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
db.execSQL("insert into person(name,salary,phone)values(?,?,?)", new Object[]{"小志志卡","13000",138438});
db.close();
}
public void delete(){
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
db.execSQL("delete from person where name = ?", new Object[]{"小志"});
db.close();
}public void updata(){
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
db.execSQL("update person set phone = ? where name = ?", new Object[]{123,"小志志卡"});
db.close();
} -
上面的方法容易出错,可以用封装好的api来进行增删改查
public void deleteApi(){
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
int i = db.delete("person", "name = ?", new String[]{"游天龙"});
db.close();
}public void updateApi(){
ContentValues values = new ContentValues();
values.put("salary", 1300);
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
db.update("person", values, "name = ?", new String[]{"游天龙"});
db.close();
}public void selectApi(){
ContentValues values = new ContentValues();
values.put("salary", 1300);
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
Cursor cursor = db.query("person", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
String salary = cursor.getString(cursor.getColumnIndex("salary"));
}
db.close();
} -
事务:要成功一起成功,要失败都失败
public void transaction(){
MyOpenHelper oh = new MyOpenHelper(getContext(), "people.db", null, 1);
SQLiteDatabase db = oh.getWritableDatabase();
db.beginTransaction();
ContentValues values = new ContentValues();
values.put("salary", 12000);
db.update("person", values, "name = ?", new String[]{"小志卡"});
values.clear();
values.put("salary", 14000);
db.update("person", values, "name = ?", new String[]{"小志志卡"});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
网友评论