1. 程式人生 > >Android SQLite資料庫demo

Android SQLite資料庫demo

demo連結:https://download.csdn.net/download/meixi_android/10710400

 

建立資料庫版本v.1

/**
 * 作者:created by meixi
 * 郵箱:[email protected]
 * 日期:2018/10/9 11
 */
public class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "mall.db";
    private static final int DATABASE_VERSION = 1000;

    private static DBHelper instance = null;


    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public synchronized static DBHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL.CREATE_TABLE_FAVORITE);

        // 若不是第一個版本安裝,直接執行資料庫升級
        // 請不要修改FIRST_DATABASE_VERSION的值,其為第一個資料庫版本大小
        final int FIRST_DATABASE_VERSION = 1000;
        onUpgrade(db, FIRST_DATABASE_VERSION, DATABASE_VERSION);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 使用for實現跨版本升級資料庫
        for (int i = oldVersion; i < newVersion; i++) {
            switch (i) {

                default:
                    break;
            }
        }
    }
}

建立資料庫版本v.2

public class DBHelper2 extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "mall.db";
    private static final int DATABASE_VERSION = 1001;

    private static DBHelper2 instance = null;


    public DBHelper2(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public synchronized static DBHelper2 getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper2(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL.CREATE_TABLE_FAVORITE);

        // 若不是第一個版本安裝,直接執行資料庫升級
        // 請不要修改FIRST_DATABASE_VERSION的值,其為第一個資料庫版本大小
        final int FIRST_DATABASE_VERSION = 1000;
        onUpgrade(db, FIRST_DATABASE_VERSION, DATABASE_VERSION);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 使用for實現跨版本升級資料庫
        for (int i = oldVersion; i < newVersion; i++) {
            switch (i) {
                case 1000:
                    upgradeToVersion1001(db);
                    break;
                default:
                    break;
            }
        }
    }

    private void upgradeToVersion1001(SQLiteDatabase db){
        // favorite表新增1個欄位
        String sql1 = "ALTER TABLE "+SQL.T_FAVORITE+" ADD COLUMN deleted VARCHAR";
        db.execSQL(sql1);
    }
}

建立資料庫版本v.3

/**
 * 作者:created by meixi
 * 郵箱:[email protected]
 * 日期:2018/10/9 17
 */
public class DBHelper3 extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "mall.db";
    private static final int DATABASE_VERSION = 1002;

    private static DBHelper3 instance = null;


    public DBHelper3(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public synchronized static DBHelper3 getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper3(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL.CREATE_TABLE_FAVORITE);

        // 若不是第一個版本安裝,直接執行資料庫升級
        // 請不要修改FIRST_DATABASE_VERSION的值,其為第一個資料庫版本大小
        final int FIRST_DATABASE_VERSION = 1000;
        onUpgrade(db, FIRST_DATABASE_VERSION, DATABASE_VERSION);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 使用for實現跨版本升級資料庫
        for (int i = oldVersion; i < newVersion; i++) {
            switch (i) {
                case 1000:
                    upgradeToVersion1001(db);
                    break;
                case 1001:
                    upgradeToVersion1002(db);
                    break;

                default:
                    break;
            }
        }
    }

    private void upgradeToVersion1001(SQLiteDatabase db){
        // favorite表新增1個欄位
        String sql1 = "ALTER TABLE "+SQL.T_FAVORITE+" ADD COLUMN deleted VARCHAR";
        db.execSQL(sql1);
    }
    private void upgradeToVersion1002(SQLiteDatabase db){
        // favorite表新增2個欄位,新增新欄位只能一個欄位一個欄位加,sqlite有限制不予許一條語句加多個欄位
        String sql1 = "ALTER TABLE "+SQL.T_FAVORITE+" ADD COLUMN message VARCHAR";
        String sql2 = "ALTER TABLE "+SQL.T_FAVORITE+" ADD COLUMN type VARCHAR";
        db.execSQL(sql1);
        db.execSQL(sql2);
    }
}

 

建立資料庫語句:

public class SQL {
    public static final String T_FAVORITE = "favorite";


    public static final String CREATE_TABLE_FAVORITE =
            "CREATE TABLE IF NOT EXISTS " + T_FAVORITE + "(" +
                    "_id integer primary key autoincrement, " +
                    "title VARCHAR, " +
                    "url VARCHAR, " +
                    "createDate VARCHAR " +
                    ")";
}

實現增刪改查activity:

public class MainActivity extends AppCompatActivity {

    private static String CREATE_TABLE ="create table number(_id integer primary key autoincrement ,phone real)";

    int ab  = 0,cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1=findViewById(R.id.baocunid);
        Button button2=findViewById(R.id.duquid);
        Button button3=findViewById(R.id.shanchuid);
        Button button4=findViewById(R.id.xiugaiid);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ab++;
                boolean nn = baocun(MainActivity.this, new String[] { "114499title","rullll---htt;s=="+ab,"加入的xxx" });
                Log.i("lgq","sbbbb---"+nn);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getBai(MainActivity.this);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               String ss= Delete(MainActivity.this,"1");
                Log.i("lgq","shanchu=g==="+ss);
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String ss = updata(MainActivity.this,"");
                Log.i("lgq","xiugg=g==="+ss);
            }
        });
    }

    public static boolean baocun(Context context, String[] values) {
        SQLiteDatabase db2=null;
        DBHelper2 dbHelper = null;
        try {
            dbHelper =new DBHelper2(context);
            db2 = dbHelper.getWritableDatabase();
            db2=dbHelper.getWritableDatabase();
            db2.beginTransaction();
            db2.execSQL("insert into favorite (title,url,deleted) values (?,?,?)",values);
            db2.setTransactionSuccessful();
            db2.endTransaction();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally{

        }

    }

    public  List<String> getBai(Context context){
        List<String> list = new ArrayList<String>();
        SQLiteDatabase db2=null;
        DBHelper2 dbHelper = null;
        try {

            dbHelper= new DBHelper2(context);
            db2=dbHelper.getWritableDatabase();
            Cursor cursor =db2.rawQuery("select _id,title,deleted from favorite", null);
            while(cursor.moveToNext()){
                cd++;
//                int dbid = cursor.getInt(cursor.getColumnIndex("_id"));
                int id=cursor.getInt(cursor.getColumnIndex("_id"));
                String haoma = cursor.getString(cursor.getColumnIndex("title"))+"";
                String names = cursor.getString(cursor.getColumnIndex("deleted"));
                list.add(haoma);
                System.out.println("lgqs======"+haoma+"......."+names+"     "+cd+"    id===  "+id);
            }
            db2.setTransactionSuccessful();
            db2.endTransaction();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }

    public static String Delete(Context context,String string){
        SQLiteDatabase db2=null;
        DBHelper2 dbHelper = null;
        try {
            dbHelper =new DBHelper2(context);
            db2 = dbHelper.getWritableDatabase();
            db2=dbHelper.getWritableDatabase();
            db2.beginTransaction();
            db2.execSQL("delete from favorite where _id=?",new String[] { string });
            db2.setTransactionSuccessful();
            db2.endTransaction();
            return "成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "失敗";
        }
    }
    public static String updata(Context context,String string){
        SQLiteDatabase db2=null;
        DBHelper2 dbHelper = null;
        try {
            dbHelper =new DBHelper2(context);
            db2 = dbHelper.getWritableDatabase();
            db2=dbHelper.getWritableDatabase();
            db2.beginTransaction();
            db2.execSQL("update favorite set title ="+"2222999"+" where url =?",new String[]{"rullll---htt;s==3"});
            db2.setTransactionSuccessful();
            db2.endTransaction();
            return "成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "失敗";
        }
    }
}