SQLite数据库-学生管理系统
1.要求
- 布局文件 --------View层
- Activity文件---------Controller层
- Helper文件:建立数据库和表,版本更新
- Dao层:对数据库表中数据增删改查操作
- Entity:数据库在项目中的类,主要用于定义与数据库对象应的属性,提供get/set方法,tostring方法,有参无参构造函数。
2.参考代码
(1)项目目录结构
(2)MyHelper代码。
//数据库帮助类
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
//自定义构造
public MyHelper(@Nullable Context context, @Nullable String name, int version) {
super(context, name, null, version);
}
//创建数据库
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS student");
sqLiteDatabase.execSQL("CREATE TABLE student(id integer primary key,name varchar(20),age integer,sex integer) ");
}
//版本更新
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("Alter TABLE student add classNo integer ");
}
}
(3)Student代码。
//学生实体
public class Student implements Serializable {
//属性
private Integer id;
private String name;
private Integer age;
private Integer sex;
//构造
public Student(Integer id, String name, Integer age, Integer sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
//get & set
public Student() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
'}';
}
}
(4)StudentDao
//数据库相关操作接口
public interface StudentDao {
//添加用户
public boolean addUser(Context context, Student student);
//更新用户
public boolean updateUser(Context context,Student student);
//删除id删除
public boolean deleteUserById(Context context,Integer id);
//基于模糊查询
public List<Student> queryUserByVague(Context context,Student student);
}
(5)StudentDaoImpl
//增删改查的实现类
public class StudentDaoImpl implements StudentDao{
@Override
public boolean addUser(Context context, Student student) {
long line=0;
MyHelper helper=null;
SQLiteDatabase database=null;
try{
helper=new MyHelper(context,"studentDB",1);
database=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("id",student.getId());
values.put("name",student.getName());
values.put("age",student.getAge());
values.put("sex",student.getSex());
database.beginTransaction();
line=database.insert("student",null,values);
database.setTransactionSuccessful();
database.endTransaction();
}
catch (Exception e){
database.close();
helper.close();
return false;
}
finally{
if (line>=1){
database.close();
helper.close();
return true;
}
database.close();
helper.close();
return false;
}
}
@Override
public boolean updateUser(Context context,Student student) {
long line=0;
MyHelper helper=null;
SQLiteDatabase database=null;
try{
helper=new MyHelper(context,"studentDB",1);
database=helper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name",student.getName());
values.put("age",student.getAge());
values.put("sex",student.getSex());
database.beginTransaction();
line=database.update("student",values,"id=?",new String[]{""+student.getId()});
database.setTransactionSuccessful();
database.endTransaction();
}
catch (Exception e){
database.close();
helper.close();
return false;
}
finally{
if (line>=1){
database.close();
helper.close();
return true;
}
database.close();
helper.close();
return false;
}
}
@Override
public boolean deleteUserById(Context context,Integer id) {
MyHelper helper=null;
SQLiteDatabase database=null;
try{
helper=new MyHelper(context,"studentDB",1);
database=helper.getWritableDatabase();
database.beginTransaction();
database.execSQL("delete from student where id=?",new String[]{id+""});
database.setTransactionSuccessful();
database.endTransaction();
}
catch (Exception e){
database.close();
helper.close();
return false;
}
finally{
database.close();
helper.close();
return true;
}
}
@Override
public List<Student> queryUserByVague(Context context,Student student) {
List<Student> list=new ArrayList<Student>();
MyHelper helper=null;
SQLiteDatabase database=null;
try{
list.clear();
helper=new MyHelper(context,"studentDB",1);
database=helper.getWritableDatabase();
String id="%"+student.getId()+"%";
if (student.getId()==null){
id="%";
}
String name="%"+student.getName()+"%";
if (student.getName()==null){
name="%";
}
String age="%"+student.getAge()+"%";
if (student.getAge()==null){
age="%";
}
String sex="%"+student.getSex()+"%";
if (student.getSex()==null){
sex="%";
}
Cursor cursor=database.rawQuery("select id,name,age,ifnull(sex,-1) from student where ifnull(id,'') like ? and ifnull(name,'') like ? and ifnull(age,'') like ? and ifnull(sex,'') like ?",new String[]{id,name,age,sex});
while (cursor.moveToNext()){
Student stu=new Student(cursor.getInt(0),cursor.getString(1),cursor.getInt(2),cursor.getInt(3));
list.add(stu);
System.out.println(stu);
}
}
catch (Exception e){
database.close();
helper.close();
return null;
}
finally{
database.close();
helper.close();
return list;
}
}
}
(6)MainActivity代码。
package com.lxz.app5;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.lxz.app5.dao.StudentDao;
import com.lxz.app5.dao.StudentDaoImpl;
import com.lxz.app5.entity.Student;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//相当于controller
public class MainActivity extends AppCompatActivity {
EditText stuId,stuName,stuAge,stuSex;
Button addBtn,deleteBtn,updateBtn,queryBtn;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
//CRUD操作
queryListener();
deleteListener();
addListener();
updateListener();
}
//方法:初始化控件
private void initView(){
//输入框
stuId=findViewById(R.id.stuId);
stuName=findViewById(R.id.stuName);
stuAge=findViewById(R.id.stuAge);
stuSex=findViewById(R.id.stuSex);
//按钮
addBtn=findViewById(R.id.addBtn);
deleteBtn=findViewById(R.id.deleteBtn);
updateBtn=findViewById(R.id.updateBtn);
queryBtn=findViewById(R.id.queryBtn);
//列表项
listView=findViewById(R.id.listview);
//加载表头
View view=LayoutInflater.from(getApplicationContext()).inflate(R.layout.student_item_header,null,false);
listView.addHeaderView(view);
//设置列表项事件监听
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//点击表头清空输入框中信息
if (position==0){
stuId.setText(""); stuName.setText("");
stuAge.setText(""); stuSex.setText("");
}
//将点击的内容显示到输入框中
else{
TextView textId=view.findViewById(R.id.textId);
TextView textName=view.findViewById(R.id.textName);
TextView textAge=view.findViewById(R.id.textAge);
TextView textSex=view.findViewById(R.id.textSex);
stuId.setText(textId.getText());
stuName.setText(textName.getText());
stuAge.setText(textAge.getText());
stuSex.setText(textSex.getText());
}
}
});
}
//方法:查询的事件监听
private void queryListener(){
queryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
List<Student> students=new ArrayList<>();
students.clear();
StudentDao studentDao=new StudentDaoImpl();
Integer id=null;
String name="";
Integer age=null;
Integer sex=null;
if (!isEmpty(stuId)) {
id=Integer.parseInt(stuId.getText().toString().trim());
}
if (!isEmpty(stuName)) {
name=stuName.getText().toString().trim();
}
if (!isEmpty(stuAge)) {
age=Integer.parseInt(stuAge.getText().toString().trim());
}
if (!isEmpty(stuSex)) {
if (stuSex.getText().toString().trim().equals("male")){
sex=1;
}
if (stuSex.getText().toString().trim().equals("female")){
sex=0;
}
}
Student student=new Student(id,name,age,sex);
students=studentDao.queryUserByVague(getApplicationContext(),student);
generateListView(students);
}
});
}
//方法:判断editText中的内容是不是空
public boolean isEmpty(EditText editText){
if (editText.getText().toString().equals("")){
return true;
}
else {
return false;
}
}
//方法:生成列表项
private void generateListView(List<Student> list){
List<Map<String, String>> l=new ArrayList<>();
for (Student s:list){
Map<String, String> map=new HashMap<>();
map.put("textId",s.getId().toString());
map.put("textName",s.getName());
if (s.getSex()==-1){
map.put("textSex","未知");
}
else{
map.put("textSex",s.getSex()==0?"female":"male");
}
map.put("textAge",s.getAge().toString());
l.add(map);
}
//创建适配器
SimpleAdapter adapter=new SimpleAdapter(getApplicationContext(),l,R.layout.student_item,new String[]{"textId","textName","textSex","textAge"},new int[]{R.id.textId,R.id.textName,R.id.textSex,R.id.textAge});
listView.setAdapter(adapter);
}
//方法:查询的事件监听
private void deleteListener(){
deleteBtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
List<Student> students = new ArrayList<>();
students.clear();
StudentDao studentDao = new StudentDaoImpl();
Integer id = null;
if (!isEmpty(stuId)) {
id = Integer.parseInt(stuId.getText().toString().trim());
boolean flag = studentDao.deleteUserById(getApplicationContext(), id);
if (flag) {
Toast.makeText(MainActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "删除失败!", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(MainActivity.this, "学号不能为空!", Toast.LENGTH_SHORT).show();
}
}
});
}
//方法:更新的事件监听
private void updateListener(){
updateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StudentDao studentDao=new StudentDaoImpl();
Integer id=null;
String name="";
Integer age=null;
Integer sex=null;
if (!isEmpty(stuId)) {
id=Integer.parseInt(stuId.getText().toString().trim());
}
if (!isEmpty(stuName)) {
name=stuName.getText().toString().trim();
}
if (!isEmpty(stuAge)) {
age=Integer.parseInt(stuAge.getText().toString().trim());
}
if (!isEmpty(stuSex)) {
System.out.println(stuSex.getText().toString().trim().equals("male"));
if (stuSex.getText().toString().trim().equals("male")){
sex=1;
}
if (stuSex.getText().toString().trim().equals("female")){
sex=0;
}
}
Student student=new Student(id,name,age,sex);
boolean flag=studentDao.updateUser(getApplicationContext(),student);
if (flag){
Toast.makeText(MainActivity.this, "更新成功!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "更新失败!", Toast.LENGTH_SHORT).show();
}
}
});
}
//方法:插入的事件监听
private void addListener(){
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StudentDao studentDao=new StudentDaoImpl();
Integer id=null;
String name="";
Integer age=null;
Integer sex=null;
if (!isEmpty(stuId)) {
id=Integer.parseInt(stuId.getText().toString().trim());
}
if (!isEmpty(stuName)) {
name=stuName.getText().toString().trim();
}
if (!isEmpty(stuAge)) {
age=Integer.parseInt(stuAge.getText().toString().trim());
}
if (!isEmpty(stuSex)) {
if (stuSex.getText().toString().equals("male")){
sex=1;
}
if (stuSex.getText().toString().equals("female")){
sex=0;
}
}
Student student=new Student(id,name,age,sex);
boolean flag=studentDao.addUser(getApplicationContext(),student);
if (flag){
Toast.makeText(MainActivity.this, "添加成功!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "添加失败!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
(7)MainActivity的布局文件。
<?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"
tools:context=".MainActivity">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:stretchColumns="1">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:text="学号"
android:textSize="30dp" />
<EditText
android:id="@+id/stuId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:hint="请输入学号(ID自增)"
android:inputType="numberSigned"
android:maxLines="1"
android:textSize="30dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:text="姓名"
android:textSize="30dp" />
<EditText
android:id="@+id/stuName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:hint="请输入姓名"
android:inputType="text"
android:maxLines="1"
android:textSize="30dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:text="性别"
android:textSize="30dp" />
<EditText
android:id="@+id/stuSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:hint="请输入性别(男或女)"
android:inputType="text"
android:maxLines="1"
android:textSize="30dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:text="年龄"
android:textSize="30dp" />
<EditText
android:id="@+id/stuAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:hint="请输入年龄"
android:inputType="numberSigned"
android:maxLines="1"
android:textSize="30dp" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<Button
android:id="@+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="添加"
android:textSize="30dp" />
<Button
android:id="@+id/deleteBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="删除"
android:textSize="30dp" />
<Button
android:id="@+id/updateBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="修改"
android:textSize="30dp" />
<Button
android:id="@+id/queryBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="查询"
android:textSize="30dp" />
</LinearLayout>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
(8)student_item_header.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:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="学号"
android:textColor="@color/pink"
android:textSize="20dp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="姓名"
android:textColor="@color/pink"
android:textSize="20dp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="性别"
android:textColor="@color/pink"
android:textSize="20dp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="年龄"
android:textColor="@color/pink"
android:textSize="20dp" />
</LinearLayout>
(9)student_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/textId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="学号"
android:textColor="@color/pink"
android:textSize="20dp" />
<TextView
android:id="@+id/textName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="姓名"
android:textColor="@color/pink"
android:textSize="20dp" />
<TextView
android:id="@+id/textSex"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="性别"
android:textColor="@color/pink"
android:textSize="20dp" />
<TextView
android:id="@+id/textAge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="年龄"
android:textColor="@color/pink"
android:textSize="20dp" />
</LinearLayout>
(10)效果图