DbUtils在SQLite中的应用
发布时间:2020-12-12 19:39:14 所属栏目:百科 来源:网络整理
导读:why use DbUtils ? DBUtils.PersistentDB 实现了强硬的、线程安全的、顽固的数据库连接,使用DB-API 2模块。DBUtils.PooledDB 实现了一个强硬的、线程安全的、有缓存的、可复用的数据库连接。 DbUtils作用有三: 1.丢一个SQL,给一个结果; 2.把结果包装成B
why use DbUtils ?DBUtils.PersistentDB 实现了强硬的、线程安全的、顽固的数据库连接,使用DB-API 2模块。DBUtils.PooledDB 实现了一个强硬的、线程安全的、有缓存的、可复用的数据库连接。 DbUtils用在sql数据库的查找dbutils支持返回以下类型的结果:
案例1.在MySQliteOpenHelpter类中新建库 public class MySQliteOpenHelpter extends SQLiteOpenHelper {
public MySQliteOpenHelpter(Context context,String name,SQLiteDatabase.CursorFactory factory,int version) {
super(context,name,factory,version);
}
public MySQliteOpenHelpter(Context context,String name){
this(context,null,1);//创建数据库
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists student(id integer primary key autoincrement,name varchar(20),password varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
}
}
2、Student类,包含属性和方法 @Table(name="student")//注意要导入xUtils包
public class Student {
@Column(column="id")
private String id;
private String name;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3、activity中 public class MainActivity extends Activity implements View.OnClickListener {
……
MySQliteOpenHelpter helpter = new MySQliteOpenHelpter(getApplicationContext(),"MY_FIRST_DB.db");//DB的名字
……
//通常的查询方法
Cursor cursor=database.rawQuery("select * from student",null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String name=cursor.getString(cursor.getColumnIndex("name"));
String password = cursor.getString(cursor.getColumnIndex("password"));
Log.d("cursor","用户名"+name+" 密码 "+password);
Toast.makeText(MainActivity.this,"用户名"+name+"密码 "+password,Toast.LENGTH_SHORT).show();
cursor.moveToNext();
}
//使用DbUtils查询
DbUtils dbUtils = DbUtils.create(this,"MY_FIRST_DB.db");//只需要对应库的名字即可
try {
List<Student> students = dbUtils.findAll(Selector.from(Student.class));//结果包装成list的形式
for(Student student:students){
Log.d("cursor","用户名 "+student.getName()+" 密码"+student.getPassword());
}
} catch (DbException e) {
e.printStackTrace();
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |