Android中SQLite数据库操作(2)——使用SQLiteDatabase提供的方法操作数据库
2024-09-07 09:47:19
如果开发者对SQL语法不熟,甚至以前从未使用过任何数据库,Android的SQLiteDatabase提供了insert、update、delete或query语句来操作数据库。
一、insert方法
long insert(String table, String nullColumnHack, ContentValues values)
table: 代表要插入到的数据表
nullColumnHack: 代表强行插入null值的数据列的列名,当values参数为null,或者不包含任何key_value键值对时该参数有些。
values: 代表一行记录的数据
insert方法插入一条记录使用ContentValue对象封装,ContentValue类似于Map,它提供了put(String key, Object value)方法及getAsXxx(String key)方法。
//创建或打开数据库
db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()
+ "/my.db", null);
//创建数据表
db.execSQL("create table news_inf(_id integer" +
" primary key autoincrement," +
" news_title varchar(50)," +
" news_content varchar(255))"); //插入数据
ContentValues values = new ContentValues();
values.put("news_title", "title1");
values.put("news_content", "content1");
db.insert("news_inf", null, values);
二、update方法
update(String table, ContentValues values, String whereClause, String[] whereArgs)
table: 代表要更新的表
values: 代表想要更新的数据
whereClause: 满足该whereClause子句的记录将会被更新
whereArgs: 用于为whereClause子句传入参数
该方法返回受此update语句影响的记录条数。
例如:更新上表中_id > 2的 news_title的值。
//更新记录
ContentValues values2 = new ContentValues();
values2.put("news_title", "title1_update");
db.update("news_inf", values2, "_id > ?", new String[]{"2"});
三、delete方法
delete(String table, String whereClause, String[] whereArgs)
tables: 代表要删除的表名
whereClause: 满足该whereClause子句的记录将会被删除
whereArgs:用于为whereClause子句传入参数
该方法返回受此delete子句影响的记录的条数。
同update的使用相同
四、query方法
query(boolean distinct, String table, String[] columns, String whereClause, String[] selectionArgs, String groupBy, Sttring having, String orderBy, String limit)
distinct: 指定是否去除重复记录
table: 查询数据的表名
columns: 要查询的列名
whereClause: 条件查询
whereArgs:条件查询的参数
groupBy: 控制分组
having: 分组过滤
orderBy: 排序
limit: 进行分页
Cursor cursor = db.query("news_inf", new String[]{"news_content, news_title"}, null, null, null, null, null);
while(cursor.moveToNext()){
Toast.makeText(this, cursor.getString(1), 2000).show();
}
cursor.close();
最新文章
- python中的TypeError错误解决办法
- [WPF系列]-TreeView的常用事项
- OpenResty(nginx+lua) 入门
- linux mysql5.5安装与配置(转帖,在网上收集,自用)
- 2014-04-09 互联网Web安全职位面试题目汇总
- LeetCode【169. Majority Element】
- 6/19 sprint3 看板和燃尽图的更新
- dbms_sql包的用法
- There is an error in invoking javac. A full JDK (not just JRE) is required
- 好代码是管出来的——使用GitHub实现简单的CI/CD
- 数据库的未来:ORM+LINQ+RX
- bzoj4361 isn(树状数组优化dp+容斥)
- Linux内核第六节 20135332武西垚
- 不一样的go语言-不同的OO
- 使用Docker-Docker for Web Developers(2)
- HDU 1260:Tickets(DP)
- kepware http接口 GO语言开发
- Selenium2+python自动化48-登录方法(参数化)
- MySQL连接数超过限制的解决方法
- linux 命令 --if
热门文章
- Android Material风格的应用(四)--FloatActionButton
- oled的一套stm32实验2(自己的实验)
- how to query for a list<;String>; in jdbctemplate?--转载
- 在云服务器上(CentOS)上安装Node
- error app/styles/components/iconfont.scss (Line 12: Invalid GBK character ";\xE5";)
- 微信端 h5 视频 video 自动播放
- Compmgmtlauncher.exe问题解决方法
- UICollectionView使用方法补充(照片轮播墙)
- swift学习第八天:元组
- wPaint在线绘图插件