作者:Kluter | 来源:互联网 | 2023-06-12 16:38
public class PhoneDao {
private MySQLiteOpenHelper helper;
public PhoneDao(Context context) {
helper = new MySQLiteOpenHelper(context);
}
/**
* 批量添加数据的方法
*/
public void AllInsert(List
list) {
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "insert into phone(name,brand,price)values(?,?,?)";
// 根据sql语句得到compileStatement对象
SQLiteStatement statement = db.compileStatement(sql);
// 开启事务
db.beginTransaction();
// 循环执行插入数据操作
for (Phone phone : list) {
statement.bindAllArgsAsStrings(new String[] { phone.getName(),
phone.getBrand(), phone.getPrice() });
statement.executeInsert();
}
//设置事务成功
db.setTransactionSuccessful();
//关闭事务
db.endTransaction();
//关闭数据库
db.close();
}
}
public class StudentDao {
private static final String tabName="student";
private MySQLiteOpenHelper helper;
public StudentDao(Context context){
helper = new MySQLiteOpenHelper(context);
}
/**
* 添加数据
*/
public void insert(Student student){
SQLiteDatabase db = helper.getWritableDatabase();
//设置数据
ContentValues values=new ContentValues();
//组合数据
values.put("name", student.getName());
values.put("age", student.getAge());
values.put("address", student.getAddress());
//执行添加操作
db.insert(tabName, null, values);
Log.i("TAG", "+++++++++++");
db.close();
}
/**
* 删除数据
*/
public void delete(String name){
SQLiteDatabase db = helper.getWritableDatabase();
String[] whereArgs=new String[]{"%"+name+"%"};
db.delete(tabName, "name like ?", whereArgs);
db.close();
}
/**
* 修改数据
*/
public void update(){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("age", "30");
db.update(tabName, values, "name=?", new String[]{"张三"});
db.close();
}
/**
* 查询数据
*/
public List select(){
List list=new ArrayList();
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query(tabName, null, null, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0){
//获取字段索引值
int namecolumnIndex = cursor.getColumnIndex("name");
int agecolumnIndex = cursor.getColumnIndex("age");
int addresscolumnIndex = cursor.getColumnIndex("address");
//通过新的方式
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
//获取数据
String name = cursor.getString(namecolumnIndex);
String age = cursor.getString(agecolumnIndex);
String address = cursor.getString(addresscolumnIndex);
Student student=new Student(name,age,address);
list.add(student);
// System.out.println("name="+name+" age="+age+" address="+address);
}
}
Log.i("TAG", "--------------");
cursor.close();
db.close();
return list;
}
}