設計一個簡單的學生信息管理程序,數據庫名稱創建為”ciec”,學生信息包括學號(表的主鍵)、姓名、性別、班級等,結合SQLite數據庫實現對學生信息的添加、修改、刪除與查詢操作。
實驗步驟
創建一個Activity,界面布局如圖1所示,用戶通過界面輸入或選擇學生信息,點擊添加按鈕后,將信息保存到數據庫中,並在界面中提示操作成功或失敗的信息。注意:輸入的學號為數據庫表的主鍵,學號不能為空也不能重復,需要在程序中對學號的信息進行合法性驗證。
點擊修改按鈕和刪除按鈕可以對學生信息進行相應操作,但必須預先輸入學號信息,否則提示操作無法成功。
點擊查詢按鈕后,先跳轉到新的Activity,在新的界面中展示查詢結果,要求將所有的學生信息都查詢出來,並用列表控件進行展示,界面布局如圖2所示。
圖1 圖2
寫了一天才寫完,一開始寫的時候一臉懵
說一下總共寫了6個文件,Mainactivity,Secondactivity,DatabaseHelper,還有三個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="vertical">
6
7 <LinearLayout 8 android:layout_width="match_parent"
9 android:layout_height="50dp"
10 android:orientation="horizontal">
11
12 <TextView 13 android:layout_width="match_parent"
14 android:layout_height="match_parent"
15 android:layout_weight="3"
16 android:text=" 學號 : "/>
17 <EditText 18 android:id="@+id/Stdudent_ID"
19 android:layout_width="match_parent"
20 android:layout_height="match_parent"
21 android:layout_weight="1" />
22 </LinearLayout>
23
24 <LinearLayout 25 android:layout_width="match_parent"
26 android:layout_height="50dp"
27 android:orientation="horizontal">
28
29 <TextView 30 android:layout_width="match_parent"
31 android:layout_height="match_parent"
32 android:layout_weight="3"
33 android:text=" 姓名 : "/>
34 <EditText 35 android:id="@+id/Stdudent_NAME"
36 android:layout_width="match_parent"
37 android:layout_height="match_parent"
38 android:layout_weight="1" />
39 </LinearLayout>
40
41 <LinearLayout 42 android:layout_width="match_parent"
43 android:layout_height="50dp"
44 android:orientation="horizontal">
45
46 <TextView 47 android:layout_width="102dp"
48 android:layout_height="match_parent"
49 android:text="性別" />
50
51 <RadioGroup 52 android:id="@+id/Student_SEX"
53 android:layout_width="wrap_content"
54 android:layout_height="wrap_content"
55 android:orientation="horizontal" >
56
57 <RadioButton 58 android:id="@+id/Student_BOY"
59 android:layout_width="118dp"
60 android:layout_height="match_parent"
61 android:text="男" />
62
63 <RadioButton 64 android:id="@+id/Student_GIRL"
65 android:layout_width="110dp"
66 android:layout_height="match_parent"
67 android:text="女" />
68 </RadioGroup>
69 </LinearLayout>
70
71 <LinearLayout 72 android:layout_width="match_parent"
73 android:layout_height="50dp"
74 android:orientation="horizontal">
75
76 <TextView 77 android:layout_width="match_parent"
78 android:layout_height="match_parent"
79 android:layout_weight="3"
80 android:text=" 班級 : "/>
81 <EditText 82 android:id="@+id/Student_CLASS"
83 android:layout_width="match_parent"
84 android:layout_height="match_parent"
85 android:layout_weight="1" />
86 </LinearLayout>
87
88 <LinearLayout 89 android:layout_width="match_parent"
90 android:layout_height="50dp"
91 android:orientation="horizontal">
92
93 <Button 94 android:id="@+id/Stdudent_ADD"
95 android:layout_width="match_parent"
96 android:layout_height="wrap_content"
97 android:layout_weight="1"
98 android:text="添加" />
99 <Button 100 android:id="@+id/Stdudent_MV"
101 android:layout_width="match_parent"
102 android:layout_height="wrap_content"
103 android:layout_weight="1"
104 android:text="修改" />
105 <Button 106 android:id="@+id/Stdudent_RM"
107 android:layout_width="match_parent"
108 android:layout_height="wrap_content"
109 android:layout_weight="1"
110 android:text="刪除" />
111 <Button 112 android:id="@+id/Stdudent_FIND"
113 android:layout_width="match_parent"
114 android:layout_height="wrap_content"
115 android:layout_weight="1"
116 android:text="查詢" />
117 </LinearLayout>
118
119 </LinearLayout>
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
6 <ListView 7 android:id="@+id/Student_ALL"
8 android:layout_height="fill_parent"
9 android:layout_width="fill_parent"/>
10
11 </LinearLayout>
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent">
6
7 <TextView 8 android:id="@+id/tv"
9 android:layout_width="match_parent"
10 android:layout_height="match_parent"/>
11
12 </LinearLayout>
這三個xml,第一個對應Mainactivity,后兩個對應Secondactivity。
第一次使用SQLlite,就先使用一下
熟悉用法了,就可以開始寫了
sqllite數據庫是AndroidSDK自帶的,所以我們寫一個類繼承SQLiteOpenHelper類(這是個抽象類),而且需要在這個類中實現三個方法:構造函數,onCreate,onUpgrade
1 package com.example.app; 2
3 import android.annotation.SuppressLint; 4 import android.content.Context; 5 import android.database.Cursor; 6 import android.database.sqlite.*; 7
8 public class DatabaseHelper extends SQLiteOpenHelper { //帶全部參數的構造函數,name為數據庫名稱 9 public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){ 10 super(context,name,factory,version); 11 } 12
13 @Override 14 public void onCreate(SQLiteDatabase db) { //建表
15 db.execSQL("CREATE TABLE information(\n" +
16 " id INTEGER PRIMARY KEY NOT NULL,\n" +
17 " name TEXT NOT NULL,\n" +
18 " sex TEXT NOT NULL,\n" +
19 " class TEXT NOT NULL\n" +
20 " )"); 21 db.execSQL("INSERT into information(id,name,sex,class) VALUES (202001,\"張三\",\"男\",\"嵌入式1班\");"); 22 db.execSQL("INSERT into information(id,name,sex,class) VALUES (202002,\"王樂\",\"男\",\"嵌入式1班\");"); 23 db.execSQL("INSERT into information(id,name,sex,class) VALUES (202003,\"劉小慧\",\"女\",\"網編1班\");"); 24 } 25
26 @Override 27 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//簡單demo,就不寫這個了 28
29 } 30 //只有conCreate()和onUpgrade是抽象方法,所以重寫,
31
32 }
然后寫Mainactivity,思路就是點擊相對應的按鈕做出相對應的操作
package com.example.app; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.*; public class MainActivity extends AppCompatActivity { private EditText Student_ID; private EditText Student_NAME; private EditText Student_CLASS; private RadioGroup Student_SEX; private RadioButton Student_BOY; private RadioButton Student_GIRL; private Button Stdudent_ADD; private Button Stdudent_MV; private Button Stdudent_RM; private Button Stdudent_FIND; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.homework_9_1); //5. //4.因為我們都在mainactivity上操作,所以就不提前在sqllit上建庫了,直接在這個建庫,開始運行時就把庫先建好 final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2); SQLiteDatabase db = databaseHelper.getWritableDatabase(); // 這里先用.getreadableDatebase查一下 //databaseHelper.exitDataBase(db); //1.對學號姓名班級進行實例化 Student_ID = (EditText) findViewById(R.id.Stdudent_ID); Student_NAME = (EditText) findViewById(R.id.Stdudent_NAME); Student_CLASS = (EditText) findViewById(R.id.Student_CLASS); //2.實例化和監聽性別選項 Student_SEX = (RadioGroup) findViewById(R.id.Student_SEX); Student_BOY = (RadioButton) findViewById(R.id.Student_BOY); Student_GIRL = (RadioButton) findViewById(R.id.Student_GIRL); //Student_SEX.setOnCheckedChangeListener(new MyRadioButtonListener()); //10.應該在點擊按鈕的時候獲取這個單選的值 //6.獲取輸入框的內容 // final String id = Student_ID.getText().toString().trim(); // final String name = Student_NAME.getText().toString().trim(); // final String classes = Student_CLASS.getText().toString().trim(); //3.然后寫增刪改查功能 Stdudent_ADD = (Button) findViewById(R.id.Stdudent_ADD);//增 Stdudent_ADD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String id = Student_ID.getText().toString().trim(); final String name = Student_NAME.getText().toString().trim(); final String classes = Student_CLASS.getText().toString().trim(); String sex = "0"; if (Student_GIRL.isChecked()){ sex = "女"; } if(Student_BOY.isChecked()){ sex = "男"; } //8.我們設置的是學號姓名班級和性別都不能為空,所以進行判斷 if (id.isEmpty() | name.isEmpty() | classes.isEmpty() | sex.equals("0")){//為null,則彈出提示框 使用isempty方法代替equals Toast.makeText(MainActivity.this,"請將信息全部填完!!!",Toast.LENGTH_SHORT).show(); }else{ //7.將輸入的內容插入數據庫 //9.因為學號唯一,所以我們還得判斷數據庫中是否已經存在,如果存在則肯定不能插入了,否則和修改沒啥區別了 SQLiteDatabase db = databaseHelper.getWritableDatabase(); //獲得寫入模式的數據庫 ContentValues values = new ContentValues(); //db.execSQL("select _id from information where _id = "+ id +";"); Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null); if(cursor.getCount()>0){ Toast.makeText(MainActivity.this,"學生信息已經存在!!!",Toast.LENGTH_SHORT).show(); }else { values.put("id",id); values.put("name",name); values.put("sex", sex); values.put("class",classes); db.insert("information",null,values); Toast.makeText(MainActivity.this,"增加成功!!!",Toast.LENGTH_SHORT).show(); } } } }); Stdudent_MV = (Button) findViewById(R.id.Stdudent_MV);//改 Stdudent_MV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String id = Student_ID.getText().toString().trim(); final String name = Student_NAME.getText().toString().trim(); final String classes = Student_CLASS.getText().toString().trim(); String sex = "0"; if (Student_GIRL.isChecked()){ sex = "女"; } if(Student_BOY.isChecked()){ sex = "男"; } //修改必須有學號,所以點擊修改按鈕時就會覆蓋相對應的學號的其他的值, //就是說學號必須有,如果學號對應的賬號信息被刪除,則應該提示無此學生信息 if (id.isEmpty()){ Toast.makeText(MainActivity.this,"學號不能為空!!!",Toast.LENGTH_SHORT).show(); }else { SQLiteDatabase db = databaseHelper.getWritableDatabase(); ContentValues values2 = new ContentValues(); ContentValues values3 = new ContentValues(); ContentValues values4 = new ContentValues(); Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null); if (cursor.getCount()>0){ values2.put("name",name); values3.put("sex", sex); values4.put("class",classes); db.update("information",values2,"id = ?",new String[]{id}); db.update("information",values3,"id = ?",new String[]{id}); db.update("information",values4,"id = ?",new String[]{id}); Toast.makeText(MainActivity.this,"修改成功!!!",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this,"無此學生!!!",Toast.LENGTH_SHORT).show(); } } } }); Stdudent_RM = (Button) findViewById(R.id.Stdudent_RM);//刪 Stdudent_RM.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String id = Student_ID.getText().toString().trim(); final String name = Student_NAME.getText().toString().trim(); final String classes = Student_CLASS.getText().toString().trim(); //刪除只需要有學號就可以 if(id.equals("")){ Toast.makeText(MainActivity.this,"學號不能為空!!!",Toast.LENGTH_SHORT).show(); }else { SQLiteDatabase db = databaseHelper.getWritableDatabase(); db.delete("information","id=?",new String[]{id}); Toast.makeText(MainActivity.this,"刪除成功!!!",Toast.LENGTH_SHORT).show(); } } }); Stdudent_FIND = (Button) findViewById(R.id.Stdudent_FIND);//查 Stdudent_FIND.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //這里跳轉到另一個activity startActivity(new Intent(MainActivity.this,SecondActivity.class)); } }); } // static class MyRadioButtonListener implements RadioGroup.OnCheckedChangeListener { //單選的類 // @Override // public void onCheckedChanged(RadioGroup group, int checkedId) { // String sex; // // 選中狀態改變時被觸發 // switch (checkedId) { // case R.id.Student_GIRL: // // 當用戶選擇女性時 // sex = "女"; // break; // case R.id.Student_BOY: // // 當用戶選擇男性時 // sex = "男"; // break; // } // } // } }
然后寫Secondactivity
沒啥好說的,就是查詢,然后將數據展示出來
這里說一個知識點
1 package com.example.app; 2
3 import androidx.appcompat.app.AppCompatActivity; 4 import androidx.appcompat.app.AlertDialog; 5
6 import android.database.Cursor; 7 import android.database.sqlite.SQLiteDatabase; 8 import android.text.TextUtils; 9
10 import android.os.Bundle; 11 import android.view.LayoutInflater; 12 import android.view.View; 13 import android.view.ViewGroup; 14 import android.widget.ArrayAdapter; 15 import android.widget.BaseAdapter; 16 import android.widget.ListView; 17 import android.widget.TextView; 18
19 import java.util.ArrayList; 20
21 public class SecondActivity extends AppCompatActivity { 22
23 private ListView Student_ALL; 24 String[] data; 25 ArrayList<String> stringArrayList = new ArrayList<String>(); 26
27 @Override 28 protected void onCreate(Bundle savedInstanceState) { 29 super.onCreate(savedInstanceState); 30 setContentView(R.layout.homework_9_2); 31 final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2); 32
33 Student_ALL = (ListView) findViewById(R.id.Student_ALL); 34
35 SQLiteDatabase db = databaseHelper.getWritableDatabase(); 36 Cursor cursor = db.query("information", new String[]{"id","name","sex","class"}, null, null, null, null, null); 37 String textview_data = ""; 38 //利用游標遍歷所有數據對象 39 //為了顯示全部,把所有對象連接起來,放到TextView中
40 while(cursor.moveToNext()){ 41 String qwe = cursor.getString(cursor.getColumnIndex("id")); 42 String asd = cursor.getString(cursor.getColumnIndex("name")); 43 String zxc = cursor.getString(cursor.getColumnIndex("sex")); 44 String qaz = cursor.getString(cursor.getColumnIndex("class")); 45 textview_data = qwe + "--" + asd +"--" + zxc +"--" + qaz; 46 stringArrayList.add(textview_data); 47 } 48 //利用arraylist,保存數據,然后在轉換成String[]數組
49 String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]); 50 data = stringArray; 51 //多余的一行注釋掉ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.id.LS);//新建並配置ArrayAapeter
52 MyBaseAdapter mAdapter = new MyBaseAdapter(); 53 Student_ALL.setAdapter(mAdapter); 54 } 55
56 class MyBaseAdapter extends BaseAdapter { 57
58 @Override 59 public int getCount() { 60 return data.length; 61 } 62 @Override 63 public Object getItem(int position) { 64 return null; 65 } 66 @Override 67 public long getItemId(int position) { 68 return 0; 69 } 70 @Override 71 public View getView(int position, View convertView, ViewGroup parent) { 72 ViewHolder holder; 73 if(convertView == null){ 74 convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.homework_five_2,parent,false); 75 holder = new ViewHolder(); 76 holder.mTextView = (TextView) convertView.findViewById(R.id.tv); 77 convertView.setTag(holder); 78 }else { 79 holder = (ViewHolder) convertView.getTag(); 80 } 81 holder.mTextView.setText(data[position]); 82 return convertView; 83 } 84 class ViewHolder { 85 TextView mTextView; 86 } 87 } 88 }
最后的成品:
到了總結的時候啦!
插入數據:
所謂的內容值,就是一個K,V 鍵值對,K指明字段名稱即列名稱,V指明字段值,即單元格內容。然后將這個鍵值對放到ContentValues的對象values里面,再把攜帶着鍵值對的對象values插入user表中
1 ContentValues values = new ContentValues(); 2 values.put("id",id); 3 db.insert("information",null,values);
刪除數據:
db.delete("information","id=?",new String[]{id});
第一個參數是表名,第二個參數是刪除條件,第三個參數就是你要刪除的值,簡單理解就是它會賦值給第二個參數的問號。
修改數據:
和插入數據相似,.update中的第一個參數是表名,第二個參數就是我們要修改的列名和值,第三個參數是修改條件,第四個參數是修改條件的值
1 ContentValues values2 = new ContentValues(); 2 values2.put("name",name); 3 db.update("information",values2,"id = ?",new String[]{id});
查詢數據:
頻繁的用到查詢語句,然后查詢語句也是我花時間最長的
Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null);
這句寫在插入功能,使用了Cursor游標進行查詢,后面的循環遍歷所有數據就不說了,單說一下這條語句
cursor就是游標對象,查詢函數是.query,第一個參數是表名,第二個參數就是select * from 表名 where name = “”;中的*號,第三個參數就是查詢條件(where后跟的name = ),第四個參數是查詢條件的值,再往后的幾個參數就是各種查詢約束了,在上面的查詢知識點說的很清楚。
還有一種查詢函數是.rawQuery,這種查詢方式是這樣的
.rawQuery(sql,selectionArgs)
第一個參數是sql語句,第二個參數要么是null,要么必須是一個字符串數組,還有第三個參數,沒用過不知道是啥
比如這樣
Cursor cursor = db.rawQuery("select name from * where id=?", new String[]{"1"});
這兩個函數的主要區別是rawQuery是直接使用SQL語句進行查詢的,也就是第一個參數字符串,在字符串內的“?”會被后面的String[]數組逐一對換掉;而query函數是Android自己封裝的查詢API
寫代碼的時候有好多問題要總結的,結果寫博客的時候發現都忘光了,不知道該寫什么,哭
補一張圖:
加油,未來可期!