介绍
Android 系统中集成的轻量级的数据库
路径
路径: data/data/应用程序包名/database/ ****.db
SQL语句复习
1.创建表:
create table student(_id integer primary key autoincrement,name varchar(30),age integer,address varchar(30));
2.添加数据:
insert into student values(null,‘迈克尔’,56,‘布鲁克林’);
3.修改数据:
update student set age=18,address=‘NEWYORK’ where name=‘aaa’
4 查询数据:
select * from student where 字段 = ‘值’
模糊查询: select * from 表名 where name like ‘%小%’
select * from student order by age desc 降序查询
sum(列名) 求和
max(列名) 最大值
min(列名) 最小值
avg(列名) 求平均值
count(列名) 统计记录数
insert() 插入数据
update() 修改数据
delete() 删除数据
query() 查询数据
添加数据
//添加数据
Button_insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//原生方法
String sql="insert into user (_id,name,age) values(null,?,?)";
database.execSQL(sql,new Object[]{"布雷克",30});
//安卓提供方法
// ContentValues contentValues = new ContentValues();
// //第一个是字段名,第二个是值
// contentValues.put("name","史蒂夫");
// contentValues.put("age",44);
//
// database.insert("user",null,contentValues);
}
});
删除数据
//删除数据
Button_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// String SQL="delete from user where _id=?";
// database.execSQL(SQL,new Object[]{2});
String sql="delete from user where _id=?";
database.execSQL(sql,new Object[]{"7"});
}
});
修改数据
//修改数据
Button_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ContentValues contentValues = new ContentValues();
contentValues.put("name","KOBE");
database.update("user",contentValues,"_id=?",new String[]{2+""});
}
});
查找数据
//查找数据
Button_select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//原生
// String sql="select * from user where _id=?";
// Cursor cursor = database.rawQuery(sql, new String[]{"8"});
// if(cursor!=null){
// while(cursor.moveToNext()){
// String name = cursor.getString(cursor.getColumnIndex("name"));
// Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
// }
// }
// cursor.close();
List<User> users=new ArrayList<>();
Cursor cursor =database.query("user",null,null,null,null,null,null,null);
if(cursor!=null){
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String age = cursor.getString(cursor.getColumnIndex("age"));
// Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
User user = new User();
user.setName(name);
user.setAge(Integer.parseInt(age));
users.add(user);
Toast.makeText(MainActivity.this, ""+users.size(), Toast.LENGTH_SHORT).show();
}
}
cursor.close();
}
});