[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-tools adb shell cd /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語句實現建立表.
? ??3.插入數據
? ? 使用insert方法添加數據,其實ContentValues就是一個Map,Key字段名稱,Value值.
? ? SQLiteDatabase.insert(
? ? ? ? String table, ? ? ? ? //添加數據的表名
? ? ? ? String nullColumnHack,//為某些空的列自動復制NULL
? ? ? ? ContentValues values ?//ContentValues的put()方法添加數據
? ? );
? ? 4.刪除數據
? ? 使用delete方法刪除表中數據,其中sqlHelper是繼承SQLiteDatabase自定義類的實例.
? ? SQLiteDatabase.delete(
? ? ? ? String table, ? ? ? //表名
? ? ? ? String whereClause, //約束刪除行,不指定默認刪除所有行
? ? ? ? String[] whereArgs ?//對應數據? ? );
? ? 5.更新數據? ??使用update方法可以修改數據,SQL+execSQL方法就不在敘述.
//小明的身高修改為180 SQLiteDatabase 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文件布局如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.touchimagetest.MainActivity" tools:ignore="MergeRootFrame" > <!-- 頂部 --> <RelativeLayout android:id="@+id/MyLayout_top" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_alignParentTop="true" > <!-- 標題 --> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"android:gravity="center" ><TextView android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:gravity="center"android:textSize="20sp" android:text="學號" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1"android:gravity="center"android:textSize="20sp"android:text="姓名" /><TextView android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:gravity="center"android:textSize="20sp"android:text="電話" /><TextView android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1"android:gravity="center" android:textSize="20sp" android:text="身高" /></LinearLayout> </RelativeLayout> <!-- 底部按鈕 --> <RelativeLayout android:id="@+id/MyLayout_bottom" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="90dp" android:layout_alignParentBottom="true" android:gravity="center"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"android:layout_alignParentBottom="true" ><LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="40dp"android:gravity="center" ><EditText android:id="@+id/edit_id"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:gravity="center"android:textSize="20sp" android:hint="學號" /> <EditText android:id="@+id/edit_name"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:gravity="center"android:textSize="20sp" android:hint="姓名" /> <EditText android:id="@+id/edit_tel"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:gravity="center"android:textSize="20sp" android:hint="電話" /> <EditText android:id="@+id/edit_height"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:gravity="center"android:textSize="20sp" android:hint="身高" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"android:orientation="horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="創表" /><Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="插入" /><Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="刪除" /><Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="更新" /><Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:text="查詢" /></LinearLayout> </LinearLayout> </RelativeLayout> <!-- 顯示列表 --> <RelativeLayout android:id="@+id/Content_Layout" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/MyLayout_bottom" android:layout_below="@id/MyLayout_top" android:background="#EFDFDF" > <!-- 顯示表內容 --><ListViewandroid:id="@+id/listview1"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center" ></ListView></RelativeLayout> </RelativeLayout>? ? 然后是在res/layout中添加ListView顯示的stu_item.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><TextView android:id="@+id/stu_id"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:textSize="20sp" /> <TextView android:id="@+id/stu_name"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1"android:textSize="20sp" /><TextView android:id="@+id/stu_tel"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1" android:textSize="20sp" /><TextView android:id="@+id/stu_height"android:layout_width="wrap_content" android:layout_height="wrap_content"android:layout_weight="1"android:textSize="20sp" /> </LinearLayout>? ? 再次,添加自定義類MySQLiteOpenHelper:
//添加自定義類 繼承SQLiteOpenHelper public 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;@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(View v) {try {SQLiteDatabase db = sqlHelper.getWritableDatabase();//游標查詢每條數據Cursor cursor = db.query("Student", null, null, null, null, null, null);//定義list存儲數據List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();//適配器SimpleAdapter數據綁定//錯誤:構造函數SimpleAdapter未定義 需把this修改為MainActivity.thisSimpleAdapter 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<String, Object> map = new HashMap<String, Object>();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/)
總結
以上是生活随笔為你收集整理的[Android] SQLite数据库之增删改查基础操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Android] 使用Include布
- 下一篇: [Android] AlertDialo