您的位置:首页 > 数据库

安卓中对数据库的操作(增删改查)

2015-12-20 18:08 316 查看
效果图如下:



MainActivity类如下:

package com.example.sqlitecrud;

import java.util.List;

import com.example.sqlitecrud.db.dao.StedentDao;
import com.example.sqlitecrud.domain.Student;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

private EditText etName;
private EditText etAge;
private EditText etDeleteName;
private EditText etUpdateProName;
private EditText etUpdateBackName;
private EditText etQueryOne;
private Button btAdd;
private Button btDelete;
private Button btUpdate;
private Button btQuery;
private Button btQueryAll;
private Button btDeleteAll;
private LinearLayout llContent;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去掉标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

initView();
initEvent();
}

private void initView() {
etName = (EditText) this.findViewById(R.id.et_name);
etAge = (EditText) this.findViewById(R.id.et_age);
etDeleteName = (EditText) this.findViewById(R.id.et_delete_name);
etUpdateProName = (EditText) this.findViewById(R.id.et_update_pro_name);
etUpdateBackName = (EditText) this
.findViewById(R.id.et_update_back_name);
etQueryOne = (EditText) this.findViewById(R.id.et_query_one);
btAdd = (Button) this.findViewById(R.id.bt_add);
btDelete = (Button) this.findViewById(R.id.bt_delete);
btUpdate = (Button) this.findViewById(R.id.bt_update);
btQuery = (Button) this.findViewById(R.id.bt_query);
btDeleteAll = (Button) this.findViewById(R.id.bt_delete_all);
btQueryAll = (Button) this.findViewById(R.id.bt_query_all);
llContent = (LinearLayout) this.findViewById(R.id.ll_content);

}

private void initEvent() {
btAdd.setOnClickListener(this);
btDelete.setOnClickListener(this);
btUpdate.setOnClickListener(this);
btQuery.setOnClickListener(this);
btQueryAll.setOnClickListener(this);
btDeleteAll.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_add:
String name = etName.getText().toString().trim();
String age = etAge.getText().toString().trim();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)) {
StedentDao dao = new StedentDao(this);
long line = dao.insert(name, Integer.valueOf(age));
Toast.makeText(this, "插入到数据库成功,影响在" + line + "行",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "输入不能为空,请重新输入", Toast.LENGTH_SHORT).show();
}
break;
case R.id.bt_delete:
String deleteName = etDeleteName.getText().toString().trim();
if (!TextUtils.isEmpty(deleteName)) {
StedentDao dao = new StedentDao(this);
int line = dao.delete(deleteName);
if (line == 0) {
Toast.makeText(this, "删除失败,数据库中不存在该人,请重新输入," + deleteName,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "数据删除成功,影响到" + line + "行",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "删除数据输入不能为空,请重新输入", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.bt_update:
String updateProName = etUpdateProName.getText().toString().trim();
String updateBackName = etUpdateBackName.getText().toString()
.trim();
if (!TextUtils.isEmpty(updateProName)
&& !TextUtils.isEmpty(updateBackName)) {
StedentDao dao = new StedentDao(this);
int line = dao.update(updateProName, updateBackName);
if (line == 0) {
Toast.makeText(this,
"修改失败,数据库中不存在该人,请重新输入," + updateProName,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
this,
"数据修改成功,将" + updateProName + "修改为" + updateBackName
+ "影响在数据库中的" + line + "行",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "修改数据输入不能为空,请重新输入", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.bt_query:
String queryOneName = etQueryOne.getText().toString().trim();
if (!TextUtils.isEmpty(queryOneName)) {
StedentDao dao = new StedentDao(this);
Student student = dao.query(queryOneName);
if (student != null) {
// 动态刷新界面
llContent.removeAllViews();
tv = new TextView(this);
tv.setText("			姓名:" + student.getName() + "						年龄:"
+ student.getAge());
tv.setTextSize(25);
tv.setTextColor(Color.GRAY);
llContent.addView(tv);
} else {
Toast.makeText(this, "未查询到任何数据", Toast.LENGTH_SHORT).show();
// 给出没有数据的提示信息
llContent.removeAllViews();
tv = new TextView(this);
tv.setText("当前没有查询到任何数据");
tv.setTextSize(25);
tv.setTextColor(Color.RED);
tv.setGravity(Gravity.CENTER);
llContent.addView(tv);
}
} else {
Toast.makeText(this, "查询数据输入不能为空,请重新输入", Toast.LENGTH_SHORT)
.show();
}
case R.id.bt_query_all:
llContent.removeAllViews();
StedentDao dao = new StedentDao(this);
List<Student> studentLists = dao.queryAll();
if (studentLists != null) {
for (Student student : studentLists) {
tv = new TextView(this);
tv.setText("			姓名:" + student.getName() + "						年龄:"
+ student.getAge());
tv.setTextSize(25);
tv.setTextColor(Color.MAGENTA);
llContent.addView(tv);
}
} else {
// 给出没有数据的提示信息
llContent.removeAllViews();
tv = new TextView(this);
tv.setText("当前没有查询到任何数据");
tv.setTextSize(25);
tv.setTextColor(Color.YELLOW);
tv.setGravity(Gravity.CENTER);
llContent.addView(tv);
Toast.makeText(this, "当前未查询到任何数据", Toast.LENGTH_SHORT).show();
}
break;
case R.id.bt_delete_all:
llContent.removeAllViews();
StedentDao deleteDao = new StedentDao(this);
int line = deleteDao.deleteAll();
if (line == 0) {
Toast.makeText(this, "所有数据删除成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "当前没有数据", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}

}

}


业务操作Dao了类:

package com.example.sqlitecrud.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.example.sqlitecrud.db.StudentSqliteOpenHelp;
import com.example.sqlitecrud.domain.Student;

public class StedentDao {

private StudentSqliteOpenHelp sSOpenHelper;

public StedentDao(Context context) {
sSOpenHelper = new StudentSqliteOpenHelp(context);
}

/**
* 往数据库中添加数据
*
* @param name
*            姓名
* @param age
*            年龄
* @return 添加到的行
*/
public long insert(String name, int age) {
SQLiteDatabase db = sSOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
return db.insert("student", null, values);
}

/**
* 从数据库中根据名字删除数据
*
* @param name
*            名字
* @return 删除的行
*/
public int delete(String name) {
SQLiteDatabase db = sSOpenHelper.getWritableDatabase();
return db.delete("student", "name = ?", new String[] { name });
}

/**
* 修改数据库中的数据
*
* @param name
*            要修改的名字
* @param newName
*            修改后的名字
* @return 修改的行数
*/
public int update(String name, String newName) {
SQLiteDatabase db = sSOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", newName);
return db.update("student", values, "name = ?", new String[] { name });
}

private Student student = null;

/**
* 根据姓名查询数据
*
* @param name
*            姓名
* @return 学生实体
*/
public Student query(String name) {
SQLiteDatabase db = sSOpenHelper.getReadableDatabase();
// String[] columns = {"id","name","age"};
Cursor cursor = db.query("student",
new String[] { "id", "name", "age" }, "name = ?",
new String[] { name }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
student = new Student();
student.setId(cursor.getInt(0));
student.setName(cursor.getString(1));
student.setAge(cursor.getInt(2));
// int id = cursor.getInt(0);
// String studentName = cursor.getString(1);
// int age = cursor.getInt(2);
}
}

return student;
}

// 存储数据的集合
private List<Student> studentList = null;

/**
* 查询所有数据
*
* @return 数据集合
*/
public List<Student> queryAll() {
SQLiteDatabase db = sSOpenHelper.getReadableDatabase();
Cursor cursor = db.query("student",
new String[] { "id", "name", "age" }, null, null, null, null,
null);
if (cursor != null && cursor.getCount() > 0) {
studentList = new ArrayList<Student>();
while (cursor.moveToNext()) {
student = new Student();
student.setId(cursor.getInt(0));
student.setName(cursor.getString(1));
student.setAge(cursor.getInt(2));
studentList.add(student);
}
}
return studentList;
}

/**
* 删除所有数据
* @return	0 删除成功,1删除失败
*/
public int deleteAll() {
try {
SQLiteDatabase db = sSOpenHelper.getWritableDatabase();
// return db.delete("student", null, null);
String sql = "delete from student";
db.execSQL(sql);
return 0;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
}


想要了解细节的童靴可以加我微信 zdliue 获取!

点我下载源码

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: