SQLite資料庫增刪改查,SQLite資料庫增刪改

來源:互聯網
上載者:User

SQLite資料庫增刪改查,SQLite資料庫增刪改

一:SQLite資料庫簡介:

     SQLite是一種輕量級的關係型資料庫,官網:http://www.sqlite.org/。

     SQLite資料庫檔案存在於行動裝置的一下目錄中:data->data->應用程式名稱->databases 。如:

二:使用SQLite資料庫首相要瞭解這兩個類:SQLiteOpenHelper   SQLiteDatabase.

      1:SQLiteOpenHelper 介紹:

  SQLiteOpenHelper:A helper class to manage database creation and version management.(一個協助類,來管理資料庫建立和資料庫版本的管理)。

 

  構造方法(Constructors):

  SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

     Create a helper object to create, open, and/or manage a database.

  SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler)

  Create a helper object to create, open, and/or manage a database.      第一個參數指定Context,參數name指定資料庫的名稱,factory為資料庫操作工廠,version為資料庫版本。  通過子類繼承實SQLiteOpenHelper 並現構造方法,調用是直接建立該類並指定參數。   公用方法(Public Methods)介紹:    2:SQLiteDatabase:Exposes methods to manage a SQLite database.(公開的方法來管理SQLite資料庫),繼承於父類:android.database.sqlite.SQLiteClosable  可通過SQLiteOpenHelper.getSQLiteDatabase獲得執行個體化:  例如:
SQLiteDatabase dbWrite = db.getWritableDatabase();

   SQLiteDatabase詳細的介紹可參照Google方法API:http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

  

三:案例展示:

      建立一個DB 類,繼承 SQLiteOpenHelper,factory制定為空白,版本指定為1,代碼如下:

    (注意:SQLite資料庫需要為表建立一個主鍵,且規定主鍵的形式為“_id”命名)

 1 package activity.cyq.sqlitelearn; 2  3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5 import android.database.sqlite.SQLiteOpenHelper; 6  7  8 public class DB extends SQLiteOpenHelper { 9     public DB(Context context) {10         super(context, "db", null, 1);11         /*db:資料庫名稱  null:操作資料庫工廠  1:資料庫版本號碼*/12     }13 14     @Override15     public void onCreate(SQLiteDatabase db) {16         db.execSQL("Create Table user( _id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT DEFAULT NONE , password TEXT DEFAULT NONE) ");17     }18 19     @Override20     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {21 22     }23 }

  案例頁面配置如下,通過添加資料按鈕實現將使用者名稱和密碼添加如資料庫中。

  布局XML檔案如下 :activity_main.xml   itemview.xml

     activity_main.xml如下:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="vertical" 6     android:paddingBottom="@dimen/activity_vertical_margin" 7     android:paddingLeft="@dimen/activity_horizontal_margin" 8     android:paddingRight="@dimen/activity_horizontal_margin" 9     android:paddingTop="@dimen/activity_vertical_margin"10     tools:context=".MainActivity">11 12     <LinearLayout13         android:layout_width="match_parent"14         android:layout_height="wrap_content"15         android:orientation="horizontal">16 17         <TextView18             android:layout_width="wrap_content"19             android:layout_height="wrap_content"20             android:layout_weight="1"21             android:text="使用者名稱:" />22 23         <EditText24             android:id="@+id/usernameEdit"25             android:layout_width="wrap_content"26             android:layout_height="wrap_content"27             android:layout_weight="6" />28 29         <TextView30             android:layout_width="wrap_content"31             android:layout_height="wrap_content"32             android:layout_weight="1"33             android:text="密碼:" />34 35         <EditText36             android:id="@+id/passwordEdit"37             android:layout_width="wrap_content"38             android:layout_height="wrap_content"39             android:layout_weight="6" />40 41         <Button42             android:id="@+id/addDataBtn"43             android:layout_width="wrap_content"44             android:layout_height="wrap_content"45             android:layout_weight="1"46             android:text="添加資料" />47 48     </LinearLayout>49 50     <RelativeLayout51         android:layout_width="match_parent"52         android:layout_height="wrap_content">53 54         <LinearLayout55             android:layout_width="match_parent"56             android:layout_height="wrap_content"57             android:layout_centerInParent="true">58 59             <TextView60                 android:layout_width="match_parent"61                 android:layout_height="wrap_content"62                 android:layout_centerInParent="true"63                 android:text="資料展示"64                 android:textSize="20dp" />65         </LinearLayout>66     </RelativeLayout>67 68     <LinearLayout69         android:layout_width="match_parent"70         android:layout_height="wrap_content">71 72         <TextView73             android:layout_width="wrap_content"74             android:layout_height="wrap_content"75             android:layout_weight="1"76             android:text="使用者名稱"77             android:textSize="20dp" />78 79         <TextView80             android:layout_width="wrap_content"81             android:layout_height="wrap_content"82             android:layout_weight="1"83             android:text="密    碼"84             android:textSize="20dp" />85     </LinearLayout>86 87     <ListView88         android:id="@android:id/list"89         android:layout_width="match_parent"90         android:layout_height="wrap_content"91         android:layout_weight="10"92         android:background="@color/material_blue_grey_800"></ListView>93 94 95 </LinearLayout>

  itemview.xml:如下:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="horizontal"> 6  7     <TextView 8         android:id="@+id/usernameItem" 9         android:layout_width="wrap_content"10         android:layout_height="wrap_content"11         android:layout_weight="1"12         android:text="username"13         android:textSize="20dp" />14 15     <TextView16         android:id="@+id/passwordItem"17         android:layout_width="wrap_content"18         android:layout_height="wrap_content"19         android:layout_weight="1"20         android:text="password"21         android:textSize="20dp" />22 23 24 </LinearLayout>

 

  MainActivity中代碼如下:

  

 1 package activity.cyq.sqlitelearn; 2  3  4 import android.app.AlertDialog; 5 import android.app.ListActivity; 6 import android.content.ContentValues; 7 import android.content.DialogInterface; 8 import android.database.Cursor; 9 import android.database.sqlite.SQLiteDatabase;10 import android.os.Bundle;11 import android.view.View;12 import android.widget.AdapterView;13 import android.widget.Button;14 import android.widget.EditText;15 import android.widget.SimpleCursorAdapter;16 17 public class MainActivity extends ListActivity implements View.OnClickListener, AdapterView.OnItemLongClickListener {18 19     private EditText username;20     private EditText password;21     private Button addData;22     private SQLiteDatabase dbWrite, dbRead;23     private SimpleCursorAdapter adapter;24     private DB db;25 26 27     @Override28     protected void onCreate(Bundle savedInstanceState) {29         super.onCreate(savedInstanceState);30         setContentView(R.layout.activity_main);31 32         username = (EditText) findViewById(R.id.usernameEdit);33         password = (EditText) findViewById(R.id.passwordEdit);34         addData = (Button) findViewById(R.id.addDataBtn);35         addData.setOnClickListener(this);36         /*建立資料庫*/37         db = new DB(MainActivity.this);38         dbWrite = db.getWritableDatabase();39         dbRead = db.getReadableDatabase();40 41         adapter = new SimpleCursorAdapter(MainActivity.this, R.layout.itemview, null, new String[]{"username", "password"},42                 new int[]{R.id.usernameItem, R.id.passwordItem});43         setListAdapter(adapter);44         refresh();45 46         getListView().setOnItemLongClickListener(this);47 48     }49 50     /*重新整理ListView資料*/51     public void refresh() {52         Cursor cursor = dbRead.query("user", null, null, null, null, null, null, null);53         adapter.changeCursor(cursor);54     }55 56     /*添加資料點擊事件*/57     @Override58     public void onClick(View v) {59         String usernameData = username.getText().toString();60         String passwordData = password.getText().toString();61         ContentValues values = new ContentValues();62         values.put("username", usernameData);63         values.put("password", passwordData);64         dbWrite.insert("user", null, values);65         values.clear();66 67         refresh();68     }69 70     /*編輯item按鈕的點擊事件*/71 72 73     /*ListViewItem的長按事件處理*/74     @Override75     public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {76 77         new AlertDialog.Builder(MainActivity.this).setTitle("警告").setMessage("是否刪除該資料").setIcon(R.drawable.delete)78                 .setPositiveButton("是", new DialogInterface.OnClickListener() {79                     @Override80                     public void onClick(DialogInterface dialog, int which) {81                         Cursor c = adapter.getCursor();82                         //  c.moveToPosition(position);/*????*/83                         int item_id = c.getInt(c.getColumnIndex("_id"));84                         dbWrite.delete("user", "_id=?", new String[]{item_id + ""});85                         refresh();86                     }87                 }).setNegativeButton("否", null)88                 .show();89 90 91         return true;92     }93 }

 

 

 

 

 

 

 

  

             

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.