1.创建数据库的帮助类SQLiteOpenHelper
onCreate()一般用于初始化数据库表。onUpgrade() 升级数据库版本 当newVersion>oldVersion时执行此方法。 一般用于更新数据库,包括删除表,添加表等各种操作.
public class MySqliteOpenHelper extends SQLiteOpenHelper{
public MySqliteOpenHelper(Context context) {
//Context,表名,游标工厂:一般用于数据库的查询,版本号
super(context, "info.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),phone varchar(11))" );
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
2.执行sql语句需要SQLiteDatabase对象,调用getReadableDatabase方法,来初始化数据库的创建
MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(context); ;
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
然后就可对数据库进行操作
3.执行完,关闭数据库对象db .close()
4.数据库的添加
通过ContentValues是用map封装的对象,用来存放值
long result = db.insert(table, nullColumnHack, values),
table: 表名 , nullColumnHack:可以为空,标示添加一个空行, values:数据一行的值 , 返回值:代表添加这个新行的Id ,-1代表添加失败.insert()底层是在拼装sql语句
public boolean add(Infobean bean) {
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
ContentValues value = new ContentValues();
value.put("name", bean.name);
value.put("phone", bean.phone);
long result = db.insert("info", null, value);
db.close();
if (result != -1) {
return true;
} else {
return false;
}
}
5.数据库的删除
int result = db.delete(table, whereClause, whereArgs);
table :表名, whereClause: 删除条件, whereArgs:条件的占位符的参数 ; 返回值:成功删除多少行
public int del(String name){
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
int result = db.delete("info", "name = ?", new String[]{name});
db.close();
return result;
}
5.数据库的修改
int result = db.update(table, values,whereClause, whereArgs);
table:表名, values:更新的值, whereClause:更新的条件, whereArgs:更新条件的占位符的值,返回值:成功修改多少行
public int update(InfoBean bean){
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("phone", bean.phone);
int result = db.update("info", values, "name = ?", new String[]{bean.name});
db.close();
return result;
}
6.数据库的查询
Cursor cursor = db.query("table ,columns, selection, selectionArgs, groupBy, having,orderBy);
table:表名, columns:查询的列名,如果null代表查询所有列; selection:查询条件, selectionArgs:条件占位符的参数值,groupBy:按什么字段分组, having:分组的条件, orderBy:按什么字段排序.返回的是一个游标对象。
游标需要关闭
public void query(String name){
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
Cursor cursor = db.query("info", new String[]{"_id","name","phone"}, "name = ?", new String[]{name}, null, null, "_id desc");
if(cursor != null && cursor.getCount() >0){
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String name_str = cursor.getString(1);
String phone = cursor.getString(2);
System.out.println("_id:"+id+";name:"+name_str+";phone:"+phone);
}
cursor.close();
}
db.close();
}
网友评论