示例创建数据库的类,并创建增加、查询、删除用户信息的方法,在其他类直接调用即可
public class UserDB {
SQLiteDatabase writableDatabase;
private static String DB_NAME = "user.db";
private static int DB_VERSION = 1;
private static String SQL = "create table userinfo("
+ "id integer primary key autoincrement,"
+ "account text,"
+ "nickname text,"
+ "sex text,"
+ "age integer,"
+ "password text)";
public static class UserDBOpenHelper extends SQLiteOpenHelper {
private Context context;
public UserDBOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists userinfo");
db.execSQL(SQL);
}
}
public void OpenUserDb(Context context) {
UserDBOpenHelper userDBOpenHelper = new UserDBOpenHelper(context);
writableDatabase = userDBOpenHelper.getWritableDatabase();
}
public long insertUserData(User user) {
String account = user.getAccount();
String nickname = user.getNickname();
String sex = user.getSex();
String password = user.getPassword();
int age = user.getAge();
ContentValues contentValues = new ContentValues();
contentValues.put("account", account);
contentValues.put("nickname", nickname);
contentValues.put("sex", sex);
contentValues.put("password", password);
contentValues.put("age", age);
return writableDatabase.insert("userinfo", null, contentValues); /
}
public List<User> FindAllUser() {
List<User> users = new ArrayList<>();
Cursor userinfo = writableDatabase.query("userinfo", null, null, null, null, null, null, null);
while (userinfo.moveToNext()) {
String account = userinfo.getString(userinfo.getColumnIndex("account"));
String nickname = userinfo.getString(userinfo.getColumnIndex("nickname"));
String sex = userinfo.getString(userinfo.getColumnIndex("sex"));
String password = userinfo.getString(userinfo.getColumnIndex("password"));
int age = Integer.parseInt(userinfo.getString(userinfo.getColumnIndex("age")));
User user = new User(account, nickname, sex, password, age);
users.add(user);
}
return users;
}
public boolean delete(String account) {
return writableDatabase.delete("userinfo", "account = ?", new String[]{account}) > 0;
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-53480.html