android 使用SQLite對資料進行增刪改查、訪問
阿新 • • 發佈:2019-01-02
功能:用SQLitem完成資料庫的動態增刪改查功能,資料的儲存於訪問 SQLite資料庫程式設計 SimpleCursorAdapter和上下文選單基本用法
開發平臺:Android Studio 3.0.1
整體框架:
見程式碼及註釋:
MainActivity.java:
package com.example.test_4application; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; importandroid.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static int DB_VERSION=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt1=(Button) findViewById(R.id.button1); Button bt2=(Button) findViewById(R.id.button2); Button bt3=(Button) findViewById(R.id.button3); Button bt4=(Button) findViewById(R.id.button4); Button bt5=(Button) findViewById(R.id.button5); Button bt6=(Button) findViewById(R.id.button6); TextView tv=(TextView)findViewById(R.id.textView1); View.OnClickListener listener=new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.button1: createdb(); break; case R.id.button2: Person person=new Person(); person.name="wustzz"; person.age=39; insert(person); break; case R.id.button3: deleteById(1); break; case R.id.button4: Person person1=new Person(); person1.name="wustzz"; person1.age=39; updateById(1,person1); break; case R.id.button5: find(); break; } } }; bt1.setOnClickListener(listener); bt2.setOnClickListener(listener); bt3.setOnClickListener(listener); bt4.setOnClickListener(listener); bt5.setOnClickListener(listener); bt6.setOnClickListener(listener); } public void createdb(){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); //呼叫getWritableDatabase()或getReadableDatabase()才會真正建立或開啟 SQLiteDatabase db=helper.getWritableDatabase(); db.close(); //操作完成後關閉資料庫連線 Toast.makeText(getApplicationContext(), "資料庫建立成功", Toast.LENGTH_SHORT).show(); } public void insert(Person person){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("INSERT INTO person VALUES (NULL, ? , ? )", new Object[ ] { person.name, person.age } ); db.close(); Toast.makeText(getApplicationContext(), "記錄新增成功", Toast.LENGTH_SHORT).show(); } public void deleteById(int id){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL( "Delete from person where id= ? " , new Object[ ]{id} ); db.close(); Toast.makeText(getApplicationContext(), "記錄刪除成功", Toast.LENGTH_SHORT).show(); } public void updateById(int id, Person person){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("Update person set name= ? , age= ? where id= ? ", new Object[ ]{ person.name,person.age, id } ); db.close(); Toast.makeText(getApplicationContext(), "記錄修改成功", Toast.LENGTH_SHORT).show(); } public void find(){ /* DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); Cursor cursor = db.rawQuery( "SELECT * FROM person where age>?", new String[]{"10"} ); TextView tv=(TextView)findViewById(R.id.textView_list); //簡單用TextView顯示一下資料 tv.setText("查詢到"+cursor.getCount()+"條記錄(當前資料庫版本號="+DB_VERSION+")"); while (cursor.moveToNext()) { //遍歷結果集 int id = cursor.getInt(cursor.getColumnIndex("id") ); String name = cursor.getString(cursor.getColumnIndex("name") ); int age = cursor.getInt(cursor.getColumnIndex("age") ); tv.setText(tv.getText()+"\n"+"id="+id+",name="+name+",age="+age); } cursor.close(); //關閉cursor db.close(); //關閉資料庫連線*/ Intent it = new Intent( MainActivity.this, ShowActivity.class ); startActivity(it); } }
上述的刪改都是靜態刪改,且都未指定要刪改的物件,讀者自己可以指定id來刪改。刪改功能後面有動態刪改實現,不同程式碼指定,直接在介面上完成。
activity_main.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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="建立資料庫和表" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="新增記錄" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="刪除記錄" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="修改記錄" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="查詢記錄" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="更新資料庫" /> </LinearLayout> <TextView android:id="@+id/textView_list" android:layout_width="match_parent" android:layout_height="match_parent" android:text="TextView" android:textSize="24sp" /> </LinearLayout>
DBHelper.java 程式碼(建立資料庫和表):
package com.example.test_4application; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by lenovo on 2018/4/28. */ public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS person (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(20)," + "age SMALLINT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS person"); //刪除資料表,謹慎使用 onCreate(db); //重新建表 } }
Person.java 程式碼(建立資料模型):
package com.example.test_4application; /** * Created by lenovo on 2018/4/28. */ public class Person { public int id; public String name; public int age; public Person(){ } public Person(String name, int age) { this.name = name; this.age = age; } }
//本實驗定義人的基本資訊資料模型類Person
ShowActivity.java 程式碼:
package com.example.test_4application; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; public class ShowActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); Cursor cursor = db.rawQuery( "SELECT id as _id, name,age FROM Person",null); String[] from = { "_id", "name", "age" }; int[] to = { R.id.txtID, R.id.txtName, R.id.txtAge }; SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.listview, cursor, from, to);//使用SimpleCursorAdapter填充ListView
//cursor.close();不能close(),否則SimpleCursorAdapter將不能從Cursor中讀取資料顯示 ListView li=(ListView)findViewById(R.id.listView1); li.setAdapter(adapter); TextView tv=(TextView)findViewById(R.id.textView_rem); tv.setText("查詢到"+cursor.getCount()+"條記錄"); ListView list1=(ListView)findViewById(R.id.listView1); registerForContextMenu( list1 ); //將上下文選單註冊到ListView上 Button bt1= (Button)findViewById(R.id.button_add); //注意id值 bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent=new Intent(ShowActivity.this,InsertActivity.class); startActivityForResult(intent, 100); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==100) if(resultCode==RESULT_OK){ onCreate(null); } // 100表明是來自於InsertActivity的回傳 if(requestCode==200) //200表明是來自於InsertActivity的回傳 if(resultCode==RESULT_OK) { onCreate(null); //ShowActivity重新執行onCreate,即完成重新整理 } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.setHeaderTitle("操作"); getMenuInflater().inflate(R.menu.managa, menu); } @Override public boolean onContextItemSelected(MenuItem item) { //新增上下文選單選中項方法 switch ( item.getItemId() ) { case R.id.delete: delete(item); //程式碼見後 return true; case R.id.update : update(item); //程式碼見後 return true; default: return false; } }
//刪除:根據id值作為刪除記錄的條件
public void delete(MenuItem item){ final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); if(info.id>0){ new AlertDialog.Builder(this).setTitle("刪除" + info.id) .setPositiveButton("確定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL( "Delete from person where id= ? ", new Object[ ]{ info.id } ); db.close(); Toast.makeText(getApplicationContext(), "記錄刪除成功", Toast.LENGTH_SHORT).show(); onCreate(null); //重新載入一次Activity,重新整理 } }) .setNegativeButton("取消", null) .show(); } }
//修改:將id值及其他欄位的值傳到UpdateActivity顯示和修改 將當前選中行的id、name、age欄位值送到UpdateActivity中去修改,後者回傳資訊public void update(MenuItem item){ final AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); Intent intent =new Intent(ShowActivity.this, UpdateActivity.class); Bundle bundle=new Bundle(); bundle.putString("id", String.valueOf(info.id)); bundle.putString("username",((TextView)info.targetView.findViewById(R.id.txtName)).getText().toString()); bundle.putString("age",((TextView)info.targetView.findViewById(R.id.txtAge)).getText().toString()); intent.putExtras(bundle); startActivityForResult(intent, 200); }}
activity_show.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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:layout_weight="1" android:orientation="horizontal"> <TextView android:id="@+id/textView_rem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="8" /> <Button android:id="@+id/button_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="新增" android:textSize="24sp" /> </LinearLayout> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout>
InsertActivity.java 程式碼:
package com.example.test_4application; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class InsertActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_insert); Button bt1= (Button)findViewById(R.id.newRec); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { EditText et1=(EditText)findViewById(R.id.editText1); EditText et2=(EditText)findViewById(R.id.editText2); Person person=new Person(et1.getText().toString(), Integer.parseInt(et2.getText().toString())); insert(person); setResult(RESULT_OK, null); //不回傳intent可設為null finish(); } }); } public void insert(Person person){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); String sql="INSERT INTO person VALUES (NULL, ?, ?)"; db.execSQL(sql, new Object[ ] { person.name, person.age } ); db.close(); Toast.makeText(getApplicationContext(), "記錄新增成功", Toast.LENGTH_SHORT).show(); } }
avtivity_insert.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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="姓名" android:textSize="24sp" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="年齡" android:textSize="24sp" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <Button android:id="@+id/newRec" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="儲存" android:textSize="24sp" /> <Button android:id="@+id/button_cancel1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="取消" android:textSize="24sp" /> </