一,实验目的
分别使用sqlite3工具和Android代码的方式建立SQLite数据库。在完成建立数据库的工作后,编程实现基本的数据库操作功能,包括数据的添加、删除和更新,
二,实验要求
创建一个学生管理的应用,基本信息包含学生姓名,班级,学号。采用数据库存储这些信息。
应用应该至少包含信息录入和删除功能。
数据显示考虑采用ListView。
三,实验报告
1使用sqlite3工具建立数据库,并实现基本数据的添加,删除功能。
(1)下面是建立学生表
创建目录:database;
然后创建数据库:student.db;
接下来创建表:studentinfo.
(2)下面实现的是往表studentinfo中添加数据
(3)下面实现的是删除表中姓名为Lily的学生信息
2下面是用代码建库,然后实现基本的添加,删除,查询功能。
MainActivity.java文件
package com.example.administrator.myapplication6; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.R.integer; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity implements OnClickListener{ private DBAdapter dbAdapter; private EditText addSnumEditText; private EditText addSnameEditText; private EditText addClassEditText; private EditText dleteBySnumEditText; private EditText findBySnumEditText; private EditText updateByIdEditText; private Button btnAdd; private Button btnFindAll; private Button btnClearShowView; private Button btnDeleteBySnum; private Button btnFindBySnum; private Button btnUpdateById; private Button btnDeleteAll; private ListView labelShow; ArrayAdapter<String> adapter; List<String>list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd = (Button)findViewById(R.id.btnAdd); btnFindAll = (Button)findViewById(R.id.btnFindAll); addSnumEditText = (EditText)findViewById(R.id.addSnum); addSnameEditText = (EditText)findViewById(R.id.addSname); addClassEditText = (EditText)findViewById(R.id.addClass); labelShow = (ListView)findViewById(R.id.labelShow); btnClearShowView = (Button)findViewById(R.id.btnClearShowView); btnDeleteBySnum = (Button)findViewById(R.id.btnDeleteBySnum); dleteBySnumEditText = (EditText)findViewById(R.id.dleteBySnumEditText); findBySnumEditText = (EditText)findViewById(R.id.findBySnumEditText); updateByIdEditText = (EditText)findViewById(R.id.updateByIdEditText); btnUpdateById = (Button)findViewById(R.id.btnUpdateById); btnFindBySnum = (Button)findViewById(R.id.btnFindBySnum); btnDeleteAll = (Button)findViewById(R.id.btnDeleteAll); btnAdd.setOnClickListener(this); btnFindAll.setOnClickListener(this); btnClearShowView.setOnClickListener(this); btnDeleteBySnum.setOnClickListener(this); btnFindBySnum.setOnClickListener(this); btnUpdateById.setOnClickListener(this); btnDeleteAll.setOnClickListener(this); dbAdapter = new DBAdapter(this); dbAdapter.open(); list = new ArrayList<String>(); adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list); labelShow.setAdapter(adapter); //ArrayAdapter tempadapter=(ArrayAdapter)labelShow.getAdapter(); showout(); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { //添加数据 case R.id.btnAdd: { Student ss = new Student(); String sno = addSnumEditText.getText().toString(); String sname = addSnameEditText.getText().toString(); String classes = addClassEditText.getText().toString(); ss.num=sno; ss.name=sname; ss.cls=classes; dbAdapter.insert(ss); Toast.makeText(this, "添加成功",Toast.LENGTH_LONG).show(); //清空上一次的文本框输入的数据 addSnumEditText.setText(""); addSnameEditText.setText(""); addClassEditText.setText(""); //跟新添加数据后的显示频 Student[] s =dbAdapter.selectAllStudent(); if(s==null) { //labelShow.setText("数据库中不存在数据"); Toast.makeText(this, "数据库中不存在数据", Toast.LENGTH_LONG).show(); return ; } else { showout(); } break; } //查询到数据库中所有的数据 case R.id.btnFindAll: { showout(); break; } //清除显示屏幕上的所有数据 case R.id.btnClearShowView: { ArrayAdapter tempadpter=(ArrayAdapter)labelShow.getAdapter(); tempadpter.clear(); Toast.makeText(this, "显示屏清除数据成功", Toast.LENGTH_LONG).show(); break; } //按照学号进行删除 case R.id.btnDeleteBySnum: { String sno = dleteBySnumEditText.getText().toString(); if ("".equals(sno)) { Toast.makeText(this, "学号不能为空", Toast.LENGTH_LONG).show(); return ; } dbAdapter.deleteBySno(sno); Toast.makeText(this, "删除成功", Toast.LENGTH_LONG).show(); break; } //删除数据库所有信息 case R.id.btnDeleteAll: { dbAdapter.deleteAll();//调用操作数据库的函数 ArrayAdapter tempadapter=(ArrayAdapter)labelShow.getAdapter(); tempadapter.clear(); break; } //根据学号查询 case R.id.btnFindBySnum: { String sno = findBySnumEditText.getText().toString(); Student[] stu = dbAdapter.selectBynum(sno);//调用函数 String ans=""; for(int i = 0 ; i < stu.length ; i++) { ans += stu[i].toString(); } Toast.makeText(this,ans,Toast.LENGTH_SHORT).show(); break; } case R.id.btnUpdateById: { String _id = updateByIdEditText.getText().toString(); if ("".equals(_id)) { Toast.makeText(this, "ID不能为空", Toast.LENGTH_LONG).show(); return ; } int id = Integer.parseInt(_id); String sno = addSnumEditText.getText().toString(); String sname = addSnameEditText.getText().toString(); String classes = addClassEditText.getText().toString(); Student ss = new Student(); ss.id=id; ss.num=sno; ss.name=sname; ss.cls=classes; dbAdapter.updateOneStudentById(id, ss); //查询更新的数据 显示出来 Student[] s =dbAdapter.selectAllStudent(); if(s==null) { //labelShow.setText("数据库中不存在数据"); Toast.makeText(this, "数据库中不存在数据", Toast.LENGTH_LONG).show(); return ; } else { showout(); } break; } default: break; } } public void showout() { Student[] stu=dbAdapter.selectAllStudent(); ArrayAdapter tempadapter=(ArrayAdapter)labelShow.getAdapter(); if(stu==null) { return; } Toast.makeText(this,"showout",Toast.LENGTH_SHORT).show(); tempadapter.clear(); for(int i=0;i<stu.length;i++) { tempadapter.add(stu[i].toString()); System.out.println("test"+stu[i].toString()); } } }
DBAdapter.java文件
package com.example.administrator.myapplication6; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; /** * Created by lh on 2018/10/29. */ public class DBAdapter { private static final String DB_NAME="student.db"; private static final String DB_TABLE="studentinfo"; private static final int DB_VERSION=1; public static final String KEY_ID="id"; public static final String KEY_NUM="num"; public static final String KEY_NAME="name"; public static final String KEY_CLASS="cls"; private SQLiteDatabase db; private final Context context; private DBOpenHelper dbOpenHelper; //private static class DBOpenHelper extends SQLiteOpenHelper{} public DBAdapter(Context _context){ context=_context; } //打开 public void open()throws SQLiteException{ dbOpenHelper=new DBOpenHelper(context,DB_NAME,null,DB_VERSION); try { db=dbOpenHelper.getWritableDatabase(); }catch (SQLiteException ex){ db=dbOpenHelper.getReadableDatabase(); } } //关闭 public void close(){ if(db!=null){ db.close(); db=null; } } //插入 public long insert(Student s) { ContentValues cv = new ContentValues(); cv.put(KEY_NUM,s.num); cv.put(KEY_NAME,s.name); cv.put(KEY_CLASS,s.cls); return db.insert(DB_TABLE,null,cv); } //查询所有学生 public Student[] selectAllStudent() { Cursor c = db.query(DB_TABLE, new String[]{KEY_ID,KEY_NUM,KEY_NAME,KEY_CLASS} , null, null, null,null, null); return convertToStudent(c); } //根据学号删除 public long deleteBySno(String num) { return db.delete(DB_TABLE, KEY_NUM+"="+num,null);//different book } //根据ID更新 public long updateOneStudentById(int id,Student s) { ContentValues cv = new ContentValues(); cv.put(KEY_NUM,s.num); cv.put(KEY_NAME,s.name); cv.put(KEY_CLASS,s.cls); return db.update(DB_TABLE, cv, "id="+id, null); } //删除所有 public long deleteAll() { return db.delete(DB_TABLE,null,null); } //查询功能 转换函数 public Student[] convertToStudent(Cursor c) { int resultsCount = c.getCount();//获得集合的数据数量 if(resultsCount==0||!c.moveToFirst())//后者指针移动到第一条 { return null; } Student []stu = new Student[resultsCount]; for (int i = 0; i < resultsCount; i++) { stu[i] = new Student(); //在cursor中提取数据 stu[i].id=c.getInt(0); stu[i].num=c.getString(c.getColumnIndex("num")); stu[i].name=c.getString(c.getColumnIndex("name")); stu[i].cls=c.getString(c.getColumnIndex("cls")); //将指针移动到下一条数据上 c.moveToNext(); } return stu; //然后就可以显示出来 } //根据学号查询 public Student[] selectBynum(String num) { Cursor c = db.query(DB_TABLE, new String[]{KEY_ID,KEY_NUM,KEY_NAME,KEY_CLASS}, KEY_NUM+"="+num, null, null, null, null); return convertToStudent(c); } private static class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } private static final String SQL = "CREATE TABLE studentinfo (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "num TEXT DEFAULT NONE," + "name TEXT DEFAULT NONE," + "cls TEXT DEFAULT NONE" + ")"; @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(SQL); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS" + DB_TABLE); onCreate(db); } } }
Student.java文件
package com.example.administrator.myapplication6; import java.io.Serializable; /** * Created by lh on 2018/11/3. */ public class Student implements Serializable { public int id=-1; public String num; public String name; public String cls; @Override public String toString() { String str="id:" + id +" " + "学号:" + num +" "+ "姓名:" + name +" "+ "班级:" + cls ; return str; } }
activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="20dp" android:text="学生管理系统" android:textSize="30dp" /> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/viewSnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="学号" /> <EditText android:id="@+id/addSnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10"> <requestFocus /> </EditText> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/viewSname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="姓名" /> <EditText android:id="@+id/addSname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/viewClass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="班级" /> <EditText android:id="@+id/addClass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> </TableLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:id="@+id/tableRow4" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加" android:layout_weight="1"/> <Button android:id="@+id/btnUpdateById" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="更新根据ID" /> <EditText android:id="@+id/updateByIdEditText" android:layout_width="120px" android:layout_height="wrap_content" android:ems="10" android:layout_weight="1"/> </TableRow> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:id="@+id/tableRow5" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/btnFindAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="查询所有" /> <Button android:id="@+id/btnFindBySnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="学号查询" /> <EditText android:id="@+id/findBySnumEditText" android:layout_width="135px" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow6" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/btnClearShowView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="清除显示" /> <Button android:id="@+id/btnDeleteBySnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="学号删除" /> <EditText android:id="@+id/dleteBySnumEditText" android:layout_width="135px" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow7" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/btnDeleteAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="全体删除" /> </TableRow> </TableLayout> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ListView android:id="@+id/labelShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> </LinearLayout> </LinearLayout>
menu文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="删除" />
</menu>
AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.myapplication6"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
结果截图:
总结:
1.首先就是将ListView运用到上面去,主要语句是:
list = new ArrayList<String>();
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
labelShow.setAdapter(adapter);
在这个地方,我开始的时候将list,adapter定义到oncreate函数里面,导致外面的函数不能使用,所以运行的时候运行出错。
2.在MainActivity.java文件中实现界面按钮的点击事件;在DBAdapter.java文件中实现的对数据库信息的操作;然后在按钮点击事件中调用在DBAdapter.java中实现的函数。