1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
public class UserDAO {
private DBHelper mDBHelper;
public UserDAO(Context context, String dbName) { mDBHelper = new DBHelper(context, dbName); }
public boolean insert(User user) { SQLiteDatabase db = null; try { db = mDBHelper.getWritableDatabase(); db.beginTransaction(); ContentValues values = new ContentValues(); values.put("account", user.account); values.put("userName", user.userName); db.insertOrThrow(DBHelper.TABLE_NAME, null, values); db.setTransactionSuccessful(); return true; } catch (SQLException e) { e.printStackTrace(); } finally { if (null != db) { try { db.endTransaction(); db.close(); } catch (Exception e) { e.printStackTrace(); } } } return false; }
public boolean delete(User user) { SQLiteDatabase db = null; try { db = mDBHelper.getWritableDatabase(); db.beginTransaction(); db.delete(DBHelper.TABLE_NAME, "account = ?", new String[]{user.account}); db.setTransactionSuccessful(); return true; } catch (Exception e) { e.printStackTrace(); } finally { if (null != db) { try { db.endTransaction(); db.close(); } catch (Exception e) { e.printStackTrace(); } } } return false; }
public List<User> getUserList() { SQLiteDatabase db = null; Cursor cursor = null;
try { db = mDBHelper.getReadableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, new String[]{"account", "userName"}, null, null, null, null, null);
if (cursor.getCount() > 0) { List<User> userList = new ArrayList<>(); while (cursor.moveToNext()) { User user = new User(cursor.getString(cursor.getColumnIndex("account")), cursor.getString(cursor.getColumnIndex("userName"))); userList.add(user); } return userList; } } catch (Exception e) { e.printStackTrace(); } finally { if (null != cursor) { try { cursor.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != db) { try { db.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; } }
|