編輯:關於 Android 開發
看過不少別人寫的 SQLite 操作示例,很多都繞得很,看半天不知道重點在哪。這個範例只做兩件事——註冊和登錄,代碼短、邏輯直白,而且已經在真實項目裡用過了,拿出來分享一下。
繼承 SQLiteOpenHelper,在 onCreate() 裡建一張用戶表。構造函數的第三個參數是 CursorFactory(一般傳 null),第四個是數據庫版本號——以後要改表結構時,就是靠遞增這個數字觸發 onUpgrade()。
public class MySqliteHelper extends SQLiteOpenHelper {
public MySqliteHelper(Context context) {
super(context, "userdb.db", null, 3);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table users(id int primary key ,name text, pwd text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 表結構變更時在這裡處理
}
}
示例代碼寫在 Activity 裡(原作者是 Fragment,若要在 Fragment 中改寫,記得把 getApplicationContext() 換成 getActivity()):
public class Userlogin extends Activity implements OnClickListener {
private MySqliteHelper helper;
Button sign;
Button reg;
String name;
String mypwd;
private EditText user;
private EditText pwd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 設置狀態欄顏色
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.StatusBar));
// 設置 ActionBar 顏色
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0099CC")));
setContentView(R.layout.login);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
user = (EditText) findViewById(R.id.editText1);
pwd = (EditText) findViewById(R.id.editText2);
}
/** 註冊:先查重,再插入 */
public void insert() {
helper = new MySqliteHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
String sql1 = "select * from users";
Cursor cursor = db.rawQuery(sql1, null);
while (cursor.moveToNext()) {
name = cursor.getString(1); // 第 2 列,索引從 0 開始
mypwd = cursor.getString(2); // 第 3 列
}
if (user.getText().toString().equals(name)) {
Toast.makeText(this, "已存在此用戶,請重新注冊", Toast.LENGTH_SHORT).show();
} else {
String sql2 = "insert into users(name,pwd) values ('"
+ user.getText().toString() + "','"
+ pwd.getText().toString() + "')";
db.execSQL(sql2);
Toast.makeText(this, "注冊成功!", Toast.LENGTH_SHORT).show();
}
}
/** 登錄:比對帳號密碼 */
public void select() {
helper = new MySqliteHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "select * from users";
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
name = cursor.getString(1);
mypwd = cursor.getString(2);
}
if (user.getText().toString().equals(name)
&& pwd.getText().toString().equals(mypwd)) {
Toast.makeText(this, "用戶驗證成功", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
this.startActivity(intent);
finish();
} else {
Toast.makeText(this, "賬號或者密碼錯誤,請重新輸入", Toast.LENGTH_SHORT).show();
}
cursor.close();
db.close();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
select();
break;
case R.id.button2:
insert();
break;
}
}
}
運行效果:

範例能跑,但如果要放進正式項目,有三處必須調整:
1. 查詢方式不對。示例用 select * from users 把全表拉回來再在 Java 裡比對,用戶量一大就會有性能問題,而且 while 迴圈裡的 name 只會留下最後一條記錄。正確做法是帶條件查詢:
Cursor cursor = db.rawQuery(
"select * from users where name = ?",
new String[]{ userName });
這樣既準確又高效。
2. SQL 拼接有注入風險。示例把用戶輸入直接拼進 SQL 字符串,一旦有人輸入 ' or '1'='1 就可能繞過驗證。上面改成 ? 佔位符 + 參數數組之後,這個問題自動解決。
3. 密碼明文存儲。數據庫裡密碼是明文,一旦設備被 root 或者數據被導出就全洩。應該存哈希值(如 SHA-256 加鹽),驗證時比對哈希而不是明文。
把這三點改掉,這份代碼就能放心用了。
來源:https://www.cnblogs.com/xiaobo-Linux/
RecyclerView 五大開源解決方案:Header、Footer、下拉刷新與上拉加載
RecyclerView 五大開源解決方案:Header、Footer、下拉刷新與上拉加載 前段時間做項目時採用了 Material Design 風格,必須用 Recy
Android 四大視圖動畫圖文詳解:Alpha、Translate、Rotate、Scale
動畫的三大家族 Android 的動畫體系分為視圖動畫(View Animation)、屬性動畫(Property Animation)與 Drawable 動畫三類。本
EventBus 3.0 快速上手:Android 事件總線入門指南
EventBus 3.0 快速上手:Android 事件總線入門指南 本文写给刚接触 EventBus 3.0 的朋友。作为 Android 开发中的常用工具,Event
Android 桌面快捷方式深度解析:適配碎片化 ROM 的實務指南
Android 桌面快捷方式深度解析:適配碎片化 ROM 的實務指南 桌面快捷方式是 App 導入流量的重要入口,也是許多產品希望用戶能快速回到應用的方式。然而,Andr