Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

SQLite 實作用戶登錄與註冊:一個完整可跑的範例

編輯:關於 Android 開發

SQLite 實作用戶登錄與註冊:一個完整可跑的範例

看過不少別人寫的 SQLite 操作示例,很多都繞得很,看半天不知道重點在哪。這個範例只做兩件事——註冊和登錄,代碼短、邏輯直白,而且已經在真實項目裡用過了,拿出來分享一下。

一、SQLiteOpenHelper:建表

繼承 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/

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved