今天这篇文章写Sqlite数据库,通过一个小案例来完整讲一下数据库常见的CRUD操作。
先对知识点总结:
SQLite数据库
-
轻量级关系型数据库
-
创建数据库需要使用的api:SQLiteOpenHelper
-
必须定义一个构造方法:
//arg1:数据库文件的名字 //arg2:游标工厂,用不到 //arg3:数据库版本,做版本升级 public MyOpenHelper(Context context, String name, CursorFactory factory, int version){}
-
数据库被创建时会调用:onCreate方法
-
数据库升级时会调用:onUpgrade方法
-
创建数据库
//创建OpenHelper对象
MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1);
//获得数据库对象,如果数据库不存在,先创建数据库,后获得,如果存在,则直接获得,
SQLiteDatabase db = oh.getWritableDatabase();
-
getWritableDatabase():打开可读写的数据库,建议
-
getReadableDatabase():在磁盘空间不足时打开只读数据库,否则打开可读写数据库,不建议
-
在创建数据库时创建表
public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("create table person (_id integer primary key autoincrement, name char(10), phone char(20), money integer(20))"); }
数据库的增删改查
SQL语句
-
insert into person (name, phone, money) values ('张三', '159874611', 2000);
-
delete from person where name = '李四' and _id = 4;
-
update person set money = 6000 where name = '李四';
-
select name, phone from person where name = '张三';
执行SQL语句实现增删改查
//插入
db.execSQL("insert into person (name, phone, money) values (?, ?, ?);", new Object[]{"张三", 15987461, 75000});
//查找
Cursor cs = db.rawQuery("select _id, name, money from person where name = ?;", new String[]{"张三"});
使用api实现增删改查
-
插入
//以键值对的形式保存要存入数据库的数据 ContentValues cv = new ContentValues(); cv.put("name", "刘能"); cv.put("phone", 1651646); cv.put("money", 3500); //返回值是改行的主键,如果出错返回-1 long i = db.insert("person", null, cv);
-
删除
//返回值是删除的行数 int i = db.delete("person", "_id = ? and name = ?", new String[]{"1", "张三"});
-
修改
ContentValues cv = new ContentValues(); cv.put("money", 25000); int i = db.update("person", cv, "name = ?", new String[]{"赵四"});
-
查询
//arg1:要查询的字段 //arg2:查询条件 //arg3:填充查询条件的占位符 Cursor cs = db.query("person", new String[]{"name", "money"}, "name = ?", new String[]{"张三"}, null, null, null); while(cs.moveToNext()){ // 获取指定列的索引值 String name = cs.getString(cs.getColumnIndex("name")); String money = cs.getString(cs.getColumnIndex("money")); System.out.println(name + ";" + money); }
开始写相关的Demo代码:
UserDB:用于创建数据和升级数据库
public class UserDB extends SQLiteOpenHelper {
public UserDB(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库,创建user表,有三个字段
db.execSQL("create table user(_id integer primary key autoincrement, " +
"name char(10), " +
"salary char(20)," +
"phone integer(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//升级数据库调用,不做处理
System.out.println("数据库升级了");
}
}
UserDao:用于CRUD,真正的对数据库的操作:
/**对数据进行CRUD的Dao层*/
public class UserDao {
//要对数据CRUD,必须拿到userDB的实例
private UserDB userDB;
public UserDao(Context context){
//创建UserDB实例
this.userDB = new UserDB(context, "user.db", null, 1);
}
//增加
public void insert(){
SQLiteDatabase database = userDB.getWritableDatabase();
//使用sql语句插入数据
database.execSQL("insert into user (name, salary, phone)values(?, ?, ?)", new Object[]{"小志的老婆", "13000", 138438});
database.execSQL("insert into user (name, salary, phone)values(?, ?, ?)", new Object[]{"小志的儿子", 14000, "13888"});
database.execSQL("insert into user (name, salary, phone)values(?, ?, ?)", new Object[]{"小志", 14000, "13888"});
//使用api插入数据
ContentValues values = new ContentValues();
//往表中的列中添加数据
values.put("name", "游天龙");//这里的键值不是随便写入的,要与数据库里面的内容一样。
values.put("salary", 16000);
values.put("phone", "15999");//这里的值可以不是字符串也可以,sqlite能把数据以字符串的形式存储进去
//利用SQLiteDatabase对象,对数据进行添加
long insert = database.insert("user", null, values);//这里的null就始终写成null就好了
System.out.println(insert);//返回值是改行的主键,如果出错返回-1
database.close();//关闭数据库
}
//修改
public void updata(){
SQLiteDatabase database = userDB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("salary", 16000);//更新数据,因此更新的数据要用ContentValues对象传递进去
//返回值:the number of rows affected
int i = database.update("user", values, "name = ?", new String[]{"游天龙"});//the number of rows affected
System.out.println(i);
database.close();
}
//删除
public void delete(){
SQLiteDatabase database = userDB.getWritableDatabase();
int i = database.delete("user", "name = ? and _id = ?", new String[]{"游天龙", "3"});
//the number of rows affected。删除了几行就返回。就是说有几行被影响了。
System.out.println(i);
database.close();
}
//查询
public List<UserBean> query(){
List<UserBean> datas = new ArrayList<UserBean>();
SQLiteDatabase database = userDB.getWritableDatabase();
Cursor cursor = database.query("user", null, null, null, null, null, null, null);
while(cursor.moveToNext()){
UserBean userBean = new UserBean();
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
String salary = cursor.getString(cursor.getColumnIndex("salary"));
userBean.setName(name);
userBean.setPhone(phone);
userBean.setSalary(salary);
datas.add(userBean);
}
database.close();
cursor.close();
return datas;
}
}
基于面向对象的思想,数据存储到javabean中
public class UserBean {
private String name;
private String phone;
private String salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
@Override
public String toString() {
return "
姓名 :" + name + "
电话 :" + phone + "
薪水 :" + salary;
}
}
最后在活动中,添加四个按钮分别进行增删改查
public class MainActivity extends Activity {
private UserDao dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dao = new UserDao(this);
}
/**增*/
public void insertApi(View v){
dao.insert();
}
/**删*/
public void deleteApi(View v){
dao.delete();
}
/**改*/
public void updateApi(View v){
dao.updata();
}
/**查*/
public void selectApi(View v){
List<UserBean> mDatas = dao.query();
//可以封装在listView等其它界面端显示
System.out.println(mDatas.toString());
}
}
最后查询后的输出结果: