Android数据存储(二)---Sqlite数据库(上)
2017-08-22 18:09
561 查看
对于更加复杂的数据结构, Android提供了内置的SQLite数据库来存储数据,SQLite使用SQL命令提供了完整的关系型数据库能力,每个使用SQLite的应用程序都有一个该数据库的实例,并且在默认情况下公限当前应用使用,数据库存存储在android设置 的/data/data/包名/databases文件夹中.
如图:
什么是Sqlite?
小型的、可嵌入、效率高、开源的、关系型数据库、程序驱动、无数据类型、支持事务操作
Sqlite的介绍
跨平台的磁盘文件,代码量少,api简单易用
Sqlite数据库的创建
SQLiteOpenHelper --> 帮助类
onCreate() --> 创建方法
onUpgrade() --> 数据库升级方法
onOpen() --> 打开数据库方法
Sqlite数据库数据类型:
Integer、varchar(10)、float、double、char(10)、text
sql创建表的语句:
create table 表名(字段名称 数据类型 约束,字段名称 数据类型 约束,......)
create table person(_id Integer primary key,name varchar(10),age Integer not null)
sql删除表的语句:
drop table 表名
drop table person
sql插入数据的语句:
insert into 表名[字段,字段] values(值1,值2,......)
insert into person[_id,age] values(1,20)
insert into person values(4,'zs',30)
sql修改数据的语句:
update 表名 set 字段=新值 where 修改条件
update person set name="ls",age="20" where _id=1
sql删除数据的语句:
delete from 表名 where 删除条件
delete from person where _id=2
sql查询数据的语句:
select 字段名 from 表名 where 查询条件 group by 分组的字段 having 筛选条件 order by 排序字段
select * from person;
其他的查询语句:
select _id,name from person
select * from person where _id=1
select * from person where _id<>1
select * from person where _id=1 and age>18
select * from person where name like "%小%"
select * from person where name like "_小%"
select * from person where name is null
select * from person where age between 10 and 20
select * from person where age>18 order by _id
数据库大致的使用步骤:
1)创建数据库
创建SqliteOpenHelper的继承类,需要传入数据库的名称。底层已经帮你创建好数据库。
2)打开数据库
使用SQLiteOpenHelper创建的helper对象
SQLiteDatabase db = helper.getReadableDatabase();
3)创建表
使用SQL语句,在自定义SQLiteOpenHelper类里面创建
db.execSQL(SQlite.CREATE_TABLE);
创建一个Android项目,先添加一个常量类:
而后创建一个SqliteOpenHelper的继承类:
这是先要添加一个bean的person类:
最后创建一个数据库的管理类:(通常不会直接去操作数据库的)
准备完毕,在布局文件里面添加几个按钮:
MainActivity.Java的操作代码:
虽然顺序不是很明显,但是代码的注释很详细,最后查询数据运行结果:
源码代码下载
如图:
什么是Sqlite?
小型的、可嵌入、效率高、开源的、关系型数据库、程序驱动、无数据类型、支持事务操作
Sqlite的介绍
跨平台的磁盘文件,代码量少,api简单易用
Sqlite数据库的创建
SQLiteOpenHelper --> 帮助类
onCreate() --> 创建方法
onUpgrade() --> 数据库升级方法
onOpen() --> 打开数据库方法
Sqlite数据库数据类型:
Integer、varchar(10)、float、double、char(10)、text
sql创建表的语句:
create table 表名(字段名称 数据类型 约束,字段名称 数据类型 约束,......)
create table person(_id Integer primary key,name varchar(10),age Integer not null)
sql删除表的语句:
drop table 表名
drop table person
sql插入数据的语句:
insert into 表名[字段,字段] values(值1,值2,......)
insert into person[_id,age] values(1,20)
insert into person values(4,'zs',30)
sql修改数据的语句:
update 表名 set 字段=新值 where 修改条件
update person set name="ls",age="20" where _id=1
sql删除数据的语句:
delete from 表名 where 删除条件
delete from person where _id=2
sql查询数据的语句:
select 字段名 from 表名 where 查询条件 group by 分组的字段 having 筛选条件 order by 排序字段
select * from person;
其他的查询语句:
select _id,name from person
select * from person where _id=1
select * from person where _id<>1
select * from person where _id=1 and age>18
select * from person where name like "%小%"
select * from person where name like "_小%"
select * from person where name is null
select * from person where age between 10 and 20
select * from person where age>18 order by _id
数据库大致的使用步骤:
1)创建数据库
创建SqliteOpenHelper的继承类,需要传入数据库的名称。底层已经帮你创建好数据库。
2)打开数据库
使用SQLiteOpenHelper创建的helper对象
SQLiteDatabase db = helper.getReadableDatabase();
3)创建表
使用SQL语句,在自定义SQLiteOpenHelper类里面创建
db.execSQL(SQlite.CREATE_TABLE);
创建一个Android项目,先添加一个常量类:
/** * Created by Layne_Yao on 2017-8-16 上午10:53:17. * CSDN:http://blog.csdn.net/Jsagacity */ public class Constant { public static final String DATABASE_NAME = "info.db";// 数据库名称 public static final int DATABASE_VERSION = 1;// 数据库的版本号 public static final String TABLE_NAME = "person";// 表名 public static final String _ID = "_id"; public static final String NAME = "name"; public static final String AGE = "age"; }
而后创建一个SqliteOpenHelper的继承类:
/** * Created by Layne_Yao on 2017-8-16 上午10:39:55. * CSDN:http://blog.csdn.net/Jsagacity */ // 提供了获取数据库对象的函数 public class MySqliteHelper extends SQLiteOpenHelper { private static final String TAG = "MySqliteHelper"; /** * 构造函数 * context 上下文对象 * name 表示创建数据库的名称 * factory 游标工厂 * version 表示创建数据库数据的版本 >=1 */ public MySqliteHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } public MySqliteHelper(Context context) { super(context, Constant.DATABASE_NAME, null, Constant.DATABASE_VERSION); } /** * 当数据库创建时回调的函数 * db 数据库对象 */ @Override public void onCreate(SQLiteDatabase db) { // // TODO Auto-generated method stub Log.e(TAG, "----------onCreate---------"); String sql = "create table " + Constant.TABLE_NAME + "(" + Constant._ID + " Integer primary key," + Constant.NAME + " varchar(10)," + Constant.AGE + " Integer not null)"; db.execSQL(sql);// 执行sql语句 } /** * 当数据库版本更新时回调的函数 * db 数据库对象 * oldVersion 数据库旧版本 * newVersion 数据库新版本 */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub Log.e(TAG, "----------onUpgrade---------"); } /** * 当数据库打开是回调的函数 * db 数据库对象 */ @Override public void onOpen(SQLiteDatabase db) { // TODO Auto-generated method stub super.onOpen(db); Log.e(TAG, "----------onOpen---------"); } }
这是先要添加一个bean的person类:
/** * Created by Layne_Yao on 2017-8-17 上午11:39:59. * CSDN:http://blog.csdn.net/Jsagacity */ public class Person { private int _id; private String name; private int age; @Override public String toString() { return "Person [_id=" + _id + ", name=" + name + ", age=" + age + "]"; } public Person(int _id, String name, int age) { this._id = _id; this.name = name; this.age = age; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
最后创建一个数据库的管理类:(通常不会直接去操作数据库的)
/** * Created by Layne_Yao on 2017-8-16 上午11:01:09. * CSDN:http://blog.csdn.net/Jsagacity */ public class DbManger { private static MySqliteHelper helper; public static MySqliteHelper getIntance(Context context){ if(helper == null){ helper = new MySqliteHelper(context); } return helper; } /** * 根据sql语句在数据库中执行语句 * db 数据库对象 * sql sql语句 */ public static void execSQL(SQLiteDatabase db,String sql){ if(db!=null){ if(sql!=null&&!"".equals(sql)){ db.execSQL(sql); } } } /** * 根据sql语句查询获得cursor对象 * db 数据库对象 * sql 查询的sql语句 * selectionArgs 查询条件的占位符 * return 查询的返回结构 */ public static Cursor selectDataBySql(SQLiteDatabase db,String sql,String[] selectionArgs){ Cursor cursor = null; if(db!=null){ cursor = db.rawQuery(sql, selectionArgs); } return cursor; } /** * 把Cursor对象转化为list数据 * cursor 游标对象 * 返回 list对象 */ public static List<Person> cursorToList(Cursor cursor){ List<Person> list = new ArrayList<>(); Person person; //moveToNext()如果返回true表示下一条记录存在,否则表示由表中数据读取完毕 while(cursor.moveToNext()){ //getColumnIndex(String columnName)根据参数中指定的字段名称获取字段下标 int columnIndex = cursor.getColumnIndex(Constant._ID); //getInt(int columnIndex)根据参数中指定的字段下标,获取对应int类型的value int _id = cursor.getInt(columnIndex); String name = cursor.getString(cursor.getColumnIndex(Constant.NAME)); int age = cursor.getInt(cursor.getColumnIndex(Constant.AGE)); person = new Person(_id, name, age); list.add(person); } return list; } }
准备完毕,在布局文件里面添加几个按钮:
<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="com.itman.sqlitedemo.MainActivity" > <Button android:id="@+id/bt_create" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="创建数据库" /> <Button android:id="@+id/bt_insert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="插入数据" /> <Button android:id="@+id/bt_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="修改数据" /> <Button android:id="@+id/bt_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="删除数据" /> <Button android:id="@+id/btn_insert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="插入数据api" /> <Button android:id="@+id/btn_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="修改数据api" /> <Button android:id="@+id/btn_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="删除数据api" /> <Button android:id="@+id/btn_select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="查询数据" /> </LinearLayout>
MainActivity.Java的操作代码:
public class MainActivity extends ActionBarActivity implements OnClickListener { private Button bt_create; private Button bt_insert; private Button bt_update; private Button bt_delete; private Button btn_insert; private Button btn_update; private Button btn_delete; private Button btn_select; private MySqliteHelper helper; private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt_create = (Button) findViewById(R.id.bt_create); bt_insert = (Button) findViewById(R.id.bt_insert); bt_update = (Button) findViewById(R.id.bt_update); bt_delete = (Button) findViewById(R.id.bt_delete); btn_insert = (Button) findViewById(R.id.btn_insert); btn_update = (Button) findViewById(R.id.btn_update); btn_delete = (Button) findViewById(R.id.btn_delete); btn_select = (Button) findViewById(R.id.btn_select); bt_create.setOnClickListener(this); bt_insert.setOnClickListener(this); bt_update.setOnClickListener(this); bt_delete.setOnClickListener(this); btn_insert.setOnClickListener(this); btn_update.setOnClickListener(this); btn_delete.setOnClickListener(this); btn_select.setOnClickListener(this); helper = DbManger.getIntance(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_create: /** * */ db = helper.getWritableDatabase(); break; case R.id.bt_insert: db = helper.getWritableDatabase(); for(int i=0;i<30;i++){ String sql = "insert into "+Constant.TABLE_NAME+" values("+i+",'zhangsan"+i+"',30)"; DbManger.execSQL(db, sql); } // String sql2 = "insert into "+Constant.TABLE_NAME+" values(2,'lisi',24)"; // DbManger.execSQL(db, sql2); db.close(); break; case R.id.bt_update: db = helper.getWritableDatabase(); String updateSql = "update "+Constant.TABLE_NAME+" set "+Constant.NAME+"='xiaohong' where _id=1"; DbManger.execSQL(db, updateSql); db.close(); break; case R.id.bt_delete: db = helper.getWritableDatabase(); String delSql = "delete from "+Constant.TABLE_NAME+" where "+Constant._ID+"=2"; DbManger.execSQL(db, delSql); db.close(); break; case R.id.btn_insert: db = helper.getWritableDatabase(); /** * insert(table, nullColumnHack, values) * table 表示插入数据表的名称 * nullColumnHack * values 键为String类型的hashMap集合 * 返回值 long 表示插入数据的列数 */ ContentValues values = new ContentValues(); values.put(Constant._ID, 3); values.put(Constant.NAME, "wangwu"); values.put(Constant.AGE, 40); long result = db.insert(Constant.TABLE_NAME, null, values); if(result>0){ Toast.makeText(MainActivity.this, "插入数据成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "插入数据失败", Toast.LENGTH_SHORT).show(); } db.close(); break; case R.id.btn_update: db = helper.getWritableDatabase(); /** * update(table, values, whereClause, whereArgs) * table 表示修改数据的表名 * values 键为String类型的hashMap集合 * whereClause 表示修改条件 * whereArgs 表示修改条件的占位符 * 返回值 count 表示修改的条数 */ ContentValues cv = new ContentValues(); cv.put(Constant.NAME, "xiaogou"); // int count = db.update(Constant.TABLE_NAME, cv, Constant._ID+"=3", null); int count = db.update(Constant.TABLE_NAME, cv, Constant._ID+"=?", new String[]{"3"}); if(count>0){ Toast.makeText(MainActivity.this, "数据修改成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "数据修改失败", Toast.LENGTH_SHORT).show(); } db.close(); break; case R.id.btn_delete: db = helper.getWritableDatabase(); /** * delete(table, whereClause, whereArgs) * table 表示删除数据表的名称 * whereClause 表示删除的条件 * whereArgs 表示删除条件的占位符 */ int conut2 = db.delete(Constant.TABLE_NAME, Constant._ID+"=?", new String[]{"3"}); if(conut2>0){ Toast.makeText(MainActivity.this, "数据删除成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "数据删除失败", Toast.LENGTH_SHORT).show(); } db.close(); break; case R.id.btn_select: //传统方式 // db = helper.getWritableDatabase(); // String selectSql = "select * from "+Constant.TABLE_NAME; // Cursor cursor = DbManger.selectDataBySql(db, selectSql, null); // List<Person> list = DbManger.cursorToList(cursor); // for (Person person : list) { // Log.e("MainActivity", person.toString()); // } // db.close(); /** * api查询方式 * query(String table, String[] columns, String selection, * String[] selectionArgs, String groupBy, String having, * String orderBy) * String table 表示查询的表名 * String[] columns 表示查询表中的字段名称 null查询所有 * String selection 表示查询条件 where 子句 * String[] selectionArgs 表示查询条件的占位符取值 * String groupBy 表示分组条件 group by 子句 * String having 表示筛选条件 having 子句 * String orderBy 表示排序条件 order by 子句 */ db = helper.getWritableDatabase(); Cursor cursor = db.query(Constant.TABLE_NAME, null, Constant._ID+">?", new String[]{"10"}, null, null, null); List<Person> list = DbManger.cursorToList(cursor); for (Person person : list) { Log.e("MainActivity", person.toString()); } db.close(); break; } } }
虽然顺序不是很明显,但是代码的注释很详细,最后查询数据运行结果:
源码代码下载
相关文章推荐
- Android开发之数据存储之二:SQLite数据库存储方式【免费提供源码下载】
- Android数据存储(3)——SQLite数据库的操作_增删改查完整输出
- android-SQLite数据库存储数据
- Android基础入门教程——6.3.1 数据存储与访问之——初见SQLite数据库
- 【Android】数据持久化补充:SQLite数据库存储
- Android数据存储方案SharePreference和SQLite数据库
- 【Android 应用开发】Android 数据存储 之 SQLite数据库详解
- Android基础之十五数据存储 之 SQLite数据库的封装
- 初学Android,数据存储之使用SQLite数据库(四十五)
- Android数据存储——SQLite数据库(模板)
- Android数据存储(SqLite数据库存储)
- Android数据存储之SQLite数据库存储
- Android上常用的几种本地数据存储方式:3、SQLite数据库存储数据
- Android数据的四种存储方式之SQLite数据库
- Android 数据存储 之 SQLite数据库详解
- 【android学习之十】——数据存储2:SQLite数据库操作
- Android开发之数据存储与访问(3)-SQLite数据库
- Android中数据的存储方式(二)—SQLite数据库
- Android 数据存储之SQLite数据库
- Android基础之十四数据存储 之 SQLite数据库详解