5.14

public class UserDao {
private SQLiteOpenHelper helper;

public UserDao(Context context) {
helper = new SQLiteOpenHelper(context, "userser", null, 1);
}

//添加数据
public long addUser(User user) {
//1.获取数据库对象
SQLiteDatabase database = helper.getWritableDatabase();
//那些列为空,可以设置为空
ContentValues values = new ContentValues();
//key是数据表的列名,value是要放进去的值
values.put("username", user.getUsername());
values.put("password", user.getPassword());
values.put("age", user.getAge());
//第一个参数表明,第二个参数自动赋值为null的列名,第三个参数数据
//返回值long,插入成功行号,插入失败-1
long i = database.insert("users", null, values);
//关闭数据库
database.close();
return i;
}

//删除
public int deleteUser(String username) {
//1.获取数据库对象
SQLiteDatabase database = helper.getWritableDatabase();
//第一个参数表明,第二个参数为删除条件,第三个参数为第二个参数中占位符所需值组成的字符串数组
int i = database.delete("users", "username=?", new String[]{username + ""});
//关闭数据库
database.close();
return i;
}

//修改
public int updateUser(User user) {
//1.获取数据库对象
SQLiteDatabase database = helper.getWritableDatabase();
//那些列为空,可以设置为空
ContentValues values = new ContentValues();
//key是数据表的列名,value是要放进去的值
values.put("username", user.getUsername());
values.put("password", user.getPassword());
values.put("age", user.getAge());
//第一个参数表明,第二个参数新数据,第三个参数是条件
int i = database.update("users", values, "username=?", new String[]{user.getUsername()});
//关闭数据库
database.close();
return i;
}

//查询
public ArrayList queryAll() {
ArrayList list = new ArrayList();
SQLiteDatabase database = helper.getWritableDatabase();
Cursor cursor = database.query("users", null, null, null, null, null, null);
list = convertFromCursor(cursor);
return list;
}

//通过对Cursor对象遍历查询结果,并将其范围为一个list集合
private ArrayList convertFromCursor(Cursor cursor) {
ArrayList list = new ArrayList();
if (cursor != null && cursor.moveToFirst()) {
//通过游标遍历这个集合
do {
@SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
@SuppressLint("Range") String username = cursor.getString(cursor.getColumnIndex("username"));
@SuppressLint("Range") String password = cursor.getString(cursor.getColumnIndex("password"));
@SuppressLint("Range") int age = cursor.getInt(cursor.getColumnIndex("age"));
User user = new User(id, username, password, age);
list.add(user);
} while (cursor.moveToNext());
}
return list;
}
}
posted @ 2024-05-15 09:50  涨涨涨张  阅读(4)  评论(0编辑  收藏  举报