主要包括数据库的创建以及数据的增、删、改、查
一、数据库的创建
BaseDao.java文件中
package com.t20.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BaseDao extends SQLiteOpenHelper {
private Context mContext;
/*
* //context上下文,name数据库名,factory游标,version数据库版本
* public BaseDao(Context context, String name, CursorFactory factory, int version) {
* super(context, name, factory, version); // TODO Auto-generated
* constructor stub }
*/
// context上下文,name数据库名,factory游标,version数据库版本
public BaseDao(Context context) {
// student.db是数据库名
super(context, "student.db", null, 1);
mContext = context;
}
/**
* 建表方法
*/
@Override
public void onCreate(SQLiteDatabase db) {
//执行建表的SQL语句
db.execSQL("create table student("
+ "id integer primary key autoincrement,"
+ "name varchar(20) not null, "
+ "sex char(2) not null)");
}
/**
* 升级数据库使用的方法
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
二、创建与数据库对应的实体类
package com.t20.entity;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Student() {
super();
}
public Student(String name,String sex) {
super();
this.name = name;
this.sex = sex;
}
public Student(Integer id,String name,String sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
}
三、定义增、删、改、查方法
StudentDaoImpl.java文件中
package com.t20.dao.impl;
import java.util.ArrayList;
import java.util.List;
import com.t20.entity.Student;
import com.t20.dao.BaseDao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class StudentDaoImpl {
private BaseDao baseDao;
public StudentDaoImpl(Context mContext) {
baseDao = new BaseDao(mContext);
}
/**
* 新增学生,往数据库中写数据
*
* @return
*/
public boolean addStudent(Student stu) {
SQLiteDatabase db = null;
try {
db = baseDao.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", stu.getName());
values.put("sex", stu.getSex());
// 第一个参数:数据库的名字
// 第二个参数:当数据库的字段不能为Null时,当插入的数据为空,会强制的将这个参数赋值给要插入的null,针对所有不为null的字段
// 第三个参数:要插入的数据
long rowId = db.insert("student", null, values);
if (rowId != -1) {// 插入成功
return true;
} else {// 插入失败
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭数据库
if (db != null) {
db.close();
}
}
return false;
}
/**
* 根据id修改数据
*
* @param stu
* @return
*/
public boolean updateStudent(Student stu) {
SQLiteDatabase db = null;
try {
db = baseDao.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", stu.getName());
values.put("sex", stu.getSex());
// 第一个参数:表名
// 第二个参数:要修改的字段
// 第三个参数:修改的条件
// 第四个参数:填充修改的条件,条件可能有多条,所以用String[]数组保存
int rowNum = db.update("student", values, "id=?",
new String[] { stu.getId() + "" });
if (rowNum > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭数据库
if (db != null) {
db.close();
}
}
return false;
}
/**
* 根据id删除数据
*
* @param stu
* @return
*/
public boolean deleteStudent(Student stu) {
SQLiteDatabase db = null;
try {
db = baseDao.getWritableDatabase();
// 第一个参数:表名
// 第二个参数:要修改的字段
// 第四个参数:填充修改的条件,条件可能有多条,所以用String[]数组保存
int rowNum = db.delete("student", "id=?",
new String[] { stu.getId() + "" });
if (rowNum > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库
if (db != null) {
db.close();
}
}
return false;
}
/**
* 查询数据
*
* @param v
* @return
*/
public List<Student> QueryStudent() {
SQLiteDatabase db = null;
List<Student> stuList = new ArrayList<Student>();
try {
db = baseDao.getReadableDatabase();
/*
* select id,name,sex from student where id=3 group by sex having
* name='aaa' order by id Desc limit 0,1
*/
// 第一个参数:强行去重,false表示允许显示两行完全相同的数据
// 第二个参数:查询的表名
// 第三个参数:要查询的字段,null相同于查询语句的*,查询全部
// 第四个参数:查询的条件,null表示没有条件
// 第五个参数:给查询的条件填充数据
// 第六个参数:分组的条件
// 第七个参数:having的条件
// 第八个参数:排序方式
// 第九个参数:查询的条数
Cursor cur = db.query(false, "student", null, null, null, null,
null, null, null);
while (cur.moveToNext()) {
// 定义学生对象
Student stu = new Student();
stu.setId(cur.getInt(cur.getColumnIndex("id")));
stu.setName(cur.getString(cur.getColumnIndex("name")));
stu.setSex(cur.getString(cur.getColumnIndex("sex")));
// 将定义好的学生对象加入到集合中
stuList.add(stu);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭数据库
if (db != null) {
db.close();
}
}
return stuList;
}
}
四、加载布局文件
activity_main.xml文件中
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/etName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:ems="10" >
<requestFocus />
</EditText>
<!-- 性别复选框 -->
<RadioGroup
android:id="@+id/rgSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/etName"
android:orientation="horizontal"
android:layout_below="@id/etName" >
<RadioButton
android:id="@+id/raMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/raFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女" />
</RadioGroup>
<!-- 插入数据 -->
<Button
android:id="@+id/btnInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rgSex"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="插入数据"
android:onClick="insert"/>
<!-- 要修改、删除数据的id -->
<EditText
android:id="@+id/etId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnUpdate"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/btnInsert"
android:ems="10" />
<!-- 修改数据 -->
<Button
android:id="@+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_below="@id/btnInsert"
android:onClick="update"
android:text="修改" />
<!-- 删除数据 -->
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/btnUpdate"
android:layout_alignBottom="@+id/btnUpdate"
android:layout_toRightOf="@+id/btnInsert"
android:onClick="delete"
android:text="删除" />
<!-- 查询数据 -->
<Button
android:id="@+id/btnQuery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/etId"
android:layout_below="@+id/etId"
android:layout_marginTop="26dp"
android:text="查询"
android:onClick="query"/>
</RelativeLayout>
五、在活动中调用定义好的方法,实现对数据的操作
MainActivity.java文件中
package com.t20.sqlite;
import java.util.List;
import com.t20.dao.impl.StudentDaoImpl;
import com.t20.entity.Student;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText etName;
private RadioGroup rgSex;
private EditText etId;
private String mSex = "男";// 性别
private StudentDaoImpl stuDaoImpl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stuDaoImpl = new StudentDaoImpl(MainActivity.this);
// 获得控件
etName = (EditText) findViewById(R.id.etName);
rgSex = (RadioGroup) findViewById(R.id.rgSex);
etId = (EditText) findViewById(R.id.etId);
// 给单选框设置监听事件,导包快捷键ctrl+shift+o
rgSex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.raMale:
mSex = "男";
break;
case R.id.raFemale:
mSex = "女";
break;
default:
break;
}
}
});
}
/**
* 新增方法
*
* @param v
*/
public void insert(View v) {
String name = etName.getText().toString();
Student stu = new Student(name, mSex);
if (stuDaoImpl.addStudent(stu)) {
Toast.makeText(MainActivity.this, "新增成功!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(MainActivity.this, "新增失败!", Toast.LENGTH_SHORT)
.show();
}
}
/**
* 根据id修改名字
*
* @param v
*/
public void update(View v) {
String name = etName.getText().toString();
// 获得id
String id = etId.getText().toString();
Student stu = new Student(Integer.parseInt(id), name, mSex);
if (stuDaoImpl.updateStudent(stu)) {
Toast.makeText(MainActivity.this, "修改成功!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(MainActivity.this, "修改失败!", Toast.LENGTH_SHORT)
.show();
}
}
/**
* 根据id删除数据
*
* @param v
*/
public void delete(View v) {
// 获得id
String id = etId.getText().toString();
String name = etName.getText().toString();
Student stu = new Student(Integer.parseInt(id), name, mSex);
if (stuDaoImpl.deleteStudent(stu)) {
Toast.makeText(MainActivity.this, "删除成功!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(MainActivity.this, "删除失败!", Toast.LENGTH_SHORT)
.show();
}
}
/**
* 查询数据
* @param v
*/
public void query(View v){
List<Student> stuList=stuDaoImpl.QueryStudent();
StringBuilder sb=new StringBuilder();
for (Student student : stuList) {
sb.append("id:"+student.getId()+"\t");
sb.append("name:"+student.getName()+"\t");
sb.append("sex:"+student.getSex()+"\n");
}
Toast.makeText(MainActivity.this, sb, Toast.LENGTH_SHORT).show();
}
}