[Android] SQLite資料庫之增刪改查基礎操作

來源:互聯網
上載者:User

[Android] SQLite資料庫之增刪改查基礎操作

在編程中經常會遇到資料庫的操作,而Android系統內建了SQLite,它是一款輕型資料庫,遵守事務ACID的關係型資料庫管理系統,它佔用的資源非常低,能夠支援Windows/Linux/Unix等主流作業系統,同時能夠跟很多程式語言如C#、PHP、Java等相結合.下面先回顧SQL的基本語句,再講述Android的基本操作.

一. adb shell回顧SQL語句

首先,我感覺自己整個大學印象最深的幾門課就包括《資料庫》,所以想先回顧SQL增刪改查的基本語句.而在Android SDK中adb是內建的調試工具,它存放在sdk的platform-tools目錄下,通過adb shell可以進入裝置控制台,操作SQL語句.

G:cd G:\software\Program software\Android\adt-bundle-windows-x86_64-20140321\sdk\platform-toolsadb shellcd /data/data/com.example.sqliteaction/databases/sqlite3 StuDatabase.db.table.schema
如下所示我先建立了SQLiteAction工程,同時在工程中建立了StuDatabase.db資料庫.輸入adb shell進入裝置控制台,調用"sqlite3+資料庫名"開啟資料庫,如果沒有db檔案則建立.


然後如所示,可以輸入SQL語句執行增刪改查.注意很容易寫錯SQL語句,如忘記")"或結束";"導致cmd中調用出錯.
--建立Teacher表create table Teacher (id integer primary key, name text);--向表中插入資料insert into Teacher (id,name) values('10001', 'Mr Wang');insert into Teacher (id,name) values('10002', 'Mr Yang');--查詢資料select * from Teacher;--更新資料update Teacher set name='Yang XZ' where id=10002;--刪除資料delete from Teacher where id=10001;


二. SQLite資料庫操作

下面講解使用SQLite操作資料庫:
1.建立開啟資料庫
使用openOrCreateDatabase函數實現,它會自動檢測是否存在該資料庫,如果存在則開啟,否則建立一個資料庫,並返回一個SQLiteDatabase對象.
2.建立表
通過定義建表的SQL語句,再調用execSQL方法執行該SQL語句實現建立表.

//建立學生表(學號,姓名,電話,身高) 主鍵學號public static final String createTableStu = "create table Student (" +"id integer primary key, " +"name text, " +"tel text, " +"height real)";//SQLiteDatabase定義db變數db.execSQL(createTableStu);
3.插入資料
使用insert方法添加資料,其實ContentValues就是一個Map,Key欄位名稱,Value值.
SQLiteDatabase.insert(
String table, //添加資料的表名
String nullColumnHack,//為某些空的列自動複製NULL
ContentValues values //ContentValues的put()方法添加資料
);

//方法一SQLiteDatabase db = sqlHelper.getWritableDatabase();ContentValues values = new ContentValues();values.put("id", "10001");values.put("name", "Eastmount");values.put("tel", "15201610000");values.put("height", "172.5");db.insert("Student", null, values);//方法二public static final String insertData = "insert into Student (" +"id, name, tel, height) values('10002','XiaoMing','110','175')";db.execSQL(insertData);
4.刪除資料
使用delete方法刪除表中資料,其中sqlHelper是繼承SQLiteDatabase自訂類的執行個體.
SQLiteDatabase.delete(
String table, //表名
String whereClause, //約束刪除行,不指定預設刪除所有行
String[] whereArgs //對應資料
);

//方法一 刪除身高>175cmSQLiteDatabase db = sqlHelper.getWritableDatabase();db.delete("Student", "height > ?", new String[] {"175"});//方法二String deleteData = "DELETE FROM Student WHERE height>175";db.execSQL(deleteData);
5.更新資料
使用update方法可以修改資料,SQL+execSQL方法就不在敘述.
//小明的身高修改為180SQLiteDatabase db = sqlHelper.getWritableDatabase();ContentValues values = new ContentValues();values.put("height", "180");db.update("Student", values, "name = ?", new String[] {"XiaoMing"});
6.其他動作

下面是關於資料庫的其他動作,其中包括使用SQL語句執行,而查詢資料Query方法由於涉及ListView顯示,請見具體執行個體.

//關閉資料庫SQLiteDatabase.close();//刪除表 執行SQL語句SQLiteDatabase.execSQL("DROP TABLE Student");//刪除資料庫this.deleteDatabase("StuDatabase.db");//查詢資料SQLiteDatabase.query();

三. 資料庫操作簡單一實例

顯示效果如所示:

首先,添加activity_main.xml檔案布局如下:

                                                                                                                                                                                                                                      
然後是在res/layout中添加ListView顯示的stu_item.xml:

             

再次,添加自訂類MySQLiteOpenHelper:

//添加自訂類 繼承SQLiteOpenHelperpublic class MySQLiteOpenHelper extends SQLiteOpenHelper {public Context mContext;//建立學生表(學號,姓名,電話,身高) 主鍵學號public static final String createTableStu = "create table Student (" +"id integer primary key, " +"name text, " +"tel text, " +"height real)";//抽象類別 必須定義顯示的建構函式 重寫方法 public MySQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {super(context, name, factory, version);mContext = context;}@Overridepublic void onCreate(SQLiteDatabase arg0) {// TODO Auto-generated method stubarg0.execSQL(createTableStu);Toast.makeText(mContext, "Created", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {// TODO Auto-generated method stubarg0.execSQL("drop table if exists Student");onCreate(arg0);Toast.makeText(mContext, "Upgraged", Toast.LENGTH_SHORT).show();}}
最後是MainActivity.java檔案,代碼如下:
public class MainActivity extends Activity {//繼承SQLiteOpenHelper類private MySQLiteOpenHelper sqlHelper;private ListView listview;private EditText edit1;private EditText edit2;private EditText edit3;private EditText edit4;@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sqlHelper = new MySQLiteOpenHelper(this, "StuDatabase.db", null, 2);        //建立新表        Button createBn = (Button) findViewById(R.id.button1);        createBn.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {        sqlHelper.getWritableDatabase();        }        });        //插入資料        Button insertBn = (Button) findViewById(R.id.button2);        edit1 = (EditText) findViewById(R.id.edit_id);        edit2 = (EditText) findViewById(R.id.edit_name);        edit3 = (EditText) findViewById(R.id.edit_tel);        edit4 = (EditText) findViewById(R.id.edit_height);        insertBn.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {        SQLiteDatabase db = sqlHelper.getWritableDatabase();        ContentValues values = new ContentValues();        /*        //插入第一組資料        values.put("id", "10001");        values.put("name", "Eastmount");        values.put("tel", "15201610000");        values.put("height", "172.5");        db.insert("Student", null, values);        */        values.put("id", edit1.getText().toString());        values.put("name", edit2.getText().toString());        values.put("tel", edit3.getText().toString());        values.put("height", edit4.getText().toString());        db.insert("Student", null, values);        Toast.makeText(MainActivity.this, "資料插入成功", Toast.LENGTH_SHORT).show();        edit1.setText("");        edit2.setText("");        edit3.setText("");        edit4.setText("");        }        });        //刪除資料        Button deleteBn = (Button) findViewById(R.id.button3);        deleteBn.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {        SQLiteDatabase db = sqlHelper.getWritableDatabase();        db.delete("Student", "height > ?", new String[] {"180"});        Toast.makeText(MainActivity.this, "刪除資料", Toast.LENGTH_SHORT).show();        }        });        //更新資料        Button updateBn = (Button) findViewById(R.id.button4);        updateBn.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {        SQLiteDatabase db = sqlHelper.getWritableDatabase();        ContentValues values = new ContentValues();        values.put("height", "180");        db.update("Student", values, "name = ?", new String[] {"XiaoMing"});        Toast.makeText(MainActivity.this, "更新資料", Toast.LENGTH_SHORT).show();        }        });        //查詢資料        listview = (ListView) findViewById(R.id.listview1);        Button selectBn = (Button) findViewById(R.id.button5);        selectBn.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {        try {        SQLiteDatabase db = sqlHelper.getWritableDatabase();        //遊標查詢每條資料        Cursor cursor = db.query("Student", null, null, null, null, null, null);        //定義list儲存資料        List> list = new ArrayList>();        //適配器SimpleAdapter資料繫結        //錯誤:建構函式SimpleAdapter未定義 需把this修改為MainActivity.this        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list, R.layout.stu_item,        new String[]{"id", "name", "tel", "height"},         new int[]{R.id.stu_id, R.id.stu_name, R.id.stu_tel, R.id.stu_height});        //讀取資料 遊標移動到下一行        while(cursor.moveToNext()) {        Map map = new HashMap();        map.put( "id", cursor.getString(cursor.getColumnIndex("id")) );        map.put( "name", cursor.getString(cursor.getColumnIndex("name")) );        map.put( "tel", cursor.getString(cursor.getColumnIndex("tel")) );        map.put( "height", cursor.getString(cursor.getColumnIndex("height")) );        list.add(map);        }        listview.setAdapter(adapter);        }        catch (Exception e){        Log.i("exception", e.toString());        }        }        });    }}
PS:希望文章對大家有所協助,文章是關於SQLite的基礎操作,而且沒有涉及到資料庫的觸發器、預存程序、事務、索引等知識,網上也有很多相關的資料.同時現在有門課程《資料庫進階技術與開發》,故作者當個線上筆記及基礎講解吧!這篇文章有一些不足之處,但作為基礎文章還是不錯的.
:http://download.csdn.net/detail/eastmount/8159881
主要參考:
1.郭霖大神的《第一行代碼Android》
2.android中的資料庫操作By:nieweilin
(By:Eastmount 2014-11-15 夜2點 http://blog.csdn.net/eastmount/)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.