android学习笔记48——SQLite
SQLite
SQLite试试一个嵌入式的数据库引擎,专门用于资源有限的设备(如手机、PDA)上适量数据存取。
SQLite支持绝大部分SQL92语法,同样允许开发者使用SQL语句操作数据库中的数据,但SQLite并不像Oracle、MySQL数据库需要安装、启动服务进程,SQLite数据库只是一个文件。
从本质上来看,SQLite的操作方式只是一种更为便捷的文件操作。
SQLiteDatebase
Android提供了SQLiteDatabase代表一个数据库(底层就是一个数据库文件),一旦应用程序获得了代表指定数据库SQLiteDatabase对象,就可通过SQLiteDatabase对象来管理、操作数据库了。
SQLiteDatebase提供如下静态方法来打开一个文件对应的数据库:
1.static SQLiteDatebase openDatabase(String path,SQLiteDatebase.CursorFactory factory,int flags)——打开path文件所代表的SQLite数据库;
2.static SQLiteDatebase openOrCreateDatabase(File file,SQLiteDatebase.CursorFactory factory)——打开或创建file文件所代表的SQLite数据库;
3.static SQLiteDatebase openOrCreateDatabase(String path,SQLiteDatebase.CursorFactory factory)——打开或创建path文件所代表的SQLite数据库;
在程序中获取SQLiteDatebase对象后,即可调用SQLiteDatebase的如下方法来操作数据库:
| execSQL(String sql,Object[] bindArgs) | 执行带占位符的SQL语句 |
| execSQL(String sql) | 执行SQL语句 |
| insert(String table,String nullColumnHack,ContentValues values) | 向执行表中插入数据 |
| update(String table,ContentValues values,String whereClause,String[] whereArgs) | 更新指定表中的特定数据 |
| delete(String table,String whereClause,String[] whereArgs) | 删除指定表中的特定数据 |
|
Cursor query(String table,String[] columns,String selection,String[] selectonArgs, String groupby,String having,String orderby) |
对执行数据表执行排序 |
|
Cursor query(String table,String[] columns,String selection,String[] selectonArgs, String groupby,String having,String orderby,String limit) |
对执行数据表执行查询。limit参数控制最多查询记录数量 (用于控制分页的参数) |
|
Cursor query(boolean distinct,String table,String[] columns,String selection,String[] selectonArgs,String groupby,String having,String orderby,String limit) |
对指定表执行查询操作,第一个参数控制是否去除重复值 |
| rawQuery(String sql,String[] selectionAgrs) | 执行带占位符的SQL语句 |
| beginTransaction | 开始事务 |
| endTransaction | 结束事务 |
以上查询方法都是返回一个Cursor对象,Android中的Cursor类似于JDBC的ResultSet,Cursor同样提供了对应的方法来移动查询结果的记录指针,如下所示:
| move(int offset) | 将记录指针向上/下移动指定的行数,offset为正数就是向下移动,为负数就是向上移动 |
| boolean moveToFirst() | 将记录指针移动到第一行,如果移动成功返回true |
| boolean moveToLast() | 将记录指针移动到最后一行,如果移动成功返回true |
| boolean moveToNext() | 将记录指针移动到下一行,如果移动成功返回true |
| boolean moveToPisition(int position) | 将记录指针移动到指定的行,如果移动成功返回true |
| boolean moveToPrevious() | 将记录指针移动到上一行,如果移动成功返回true |
一旦将记录指针移动的指定行之后,就可以调用Cursor的getXxx()方法获取该行的指定列的数据。
创建数据库和表
SQLiteDatebase可使用静态方法打开或创建数据库如下:
SQLiteDatebase.openOrCreateDatebase("/mnt/db/temp.db3",null);
——没有指定SQLiteDatebase.CursorFactory factory,该参数是一个用于返回Cursor工厂,如果指定该参数为null,则意味着使用默认的工厂。
注意:
SQLiteDatebase.openOrCreateDatebase("/mnt/db/temp.db3",null);可返回一个SQLiteDatebase对象,
该对象的execSQL可执行任意的SQL语句,因此程序可通过如下代码创建数据库表:
sql="create table userInfo (id integer primary key,name varchar(50))";
db.execSQL(sql);
使用SQL语句操作SQLite数据库
如以上所提,SQLiteDatebase的execSQL方法可执行任意SQL语句,包括带占位符的SQL语句。
但由于该方法没有返回值,一般用于执行DDL语句或DML语句,如果需要执行查询语句,则可调用SQLiteDatebase的rawQuery(String sql,String[] selecttionArgs)方法.
Eg:如下代码可执行DML语句:
db.execSQL("insert into tableInfo values(null,?,?)",new String[]{title,content});
sql组成:
DDL:数据库模式定义语言,关键字:create
DML:数据操纵语言,关键字:Insert、delete、update
DCL:数据库控制语言 ,关键字:grant、remove
DQL:数据库查询语言,关键字:select
实例如下:
布局文件==》main.xml
<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=".MainActivity" > <EditText
android:id="@+id/editOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" /> <EditText
android:id="@+id/editTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" /> <Button
android:id="@+id/btnInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="insert" /> <ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout> ==>line.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" > <TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout> 实现代码
package com.example.mysqlite1; import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter; public class MainActivity extends Activity
{
EditText Edit1;
EditText Edit2;
SQLiteDatabase db; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String filePath = this.getFilesDir().toString() + "my.db3";
db = SQLiteDatabase.openOrCreateDatabase(filePath, null);
Edit1 = (EditText) this.findViewById(R.id.editOne);
Edit2 = (EditText) this.findViewById(R.id.editTwo); Button btnInsert = (Button) this.findViewById(R.id.btnInsert); btnInsert.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
InsertDataAndInflateList();
} catch (Exception e)
{
Log.i("swg", "error" + e.getMessage());
db.execSQL("create table SQLiteTest2(_id integer primary key autoincrement,text1 varchar(50),text2 varchar(50))");
InsertDataAndInflateList();
} } private void InsertDataAndInflateList()
{
insertData(db, Edit1.getText().toString(), Edit2.getText().toString());
Cursor crusor = db.rawQuery("select * from SQLiteTest2", null);
Log.i("swg", "查询完成");
inflateList(crusor);
} private void insertData(SQLiteDatabase db, String text, String text2)
{
db.execSQL("insert into SQLiteTest2 values(null,?,?)", new String[] { text, text2 });
Log.i("swg", "插入成功");
} @SuppressWarnings("deprecation")
private void inflateList(Cursor crusor)
{
Log.i("swg", "inflateList");
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.line, crusor, new String[] { "text1", "text2" }, new int[] {
R.id.tv1, R.id.tv2 }); Log.i("swg", "inflateList==" + adapter.getCount()); ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(adapter);
}
});
} @Override
protected void onDestroy()
{
super.onDestroy();
// 退出时关闭SQLiteDatabase
if (db != null && db.isOpen())
db.close();
} @Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }
运行效果;

注意:使用SimpleCursorAdapter封装Cursor时要求底层数据表中的主键列的列名为_id,SimpleCursorAdapter只能识别列名为_id的主键。
因此以上实例中创建表时,主键列名为_id.否则就会出现java.lang.IllegalArgumentException:column '_id' does not exist异常。
总结:
使用SQLiteDatabase进行数据库操作的步骤如下:
1.获取SQLiteDatabase对象,其代表了与数据库的连接;
2.调用SQLiteDatabase的方法执行SQL语句;
3.操作SQL语句的执行结果,例如:用SimpleCursorAdapter封装Cursor;
4.管理SQLiteDatabase,回收资源。
android学习笔记48——SQLite的更多相关文章
- Android学习笔记(SQLite的简单使用)
1.SQLite介绍 SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中.它是D.RichardHipp建立的公有领域项目.它的设计目标是嵌入式的,而且 ...
- android学习笔记51——SQLite 手势Gesture
手势Gesture 所谓手势,是指用户手指或触摸笔在触摸屏幕上的连续触碰行为. Androi对两种手势行为都提供了支持: 1.对于第一种手势而言,android提供了手势检测,并为手势检测提供了相应的 ...
- Android学习笔记36:使用SQLite方式存储数据
在Android中一共提供了5种数据存储方式,分别为: (1)Files:通过FileInputStream和FileOutputStream对文件进行操作.具体使用方法可以参阅博文<Andro ...
- 【转】 Pro Android学习笔记(五五):调试和分析(3):adb命令、模拟器控制台和StrictMode
目录(?)[-] adb命令 模拟器Console StrictMode adb命令 我们在学习SQLite的使用,介绍过部分adb命令的使用,见Pro Android学习笔记(五):了解Conten ...
- 【转】Pro Android学习笔记(七):了解Content Provider(下上)
我们通过一个Content Provider小例子进行详细说明.数据源是一个SQLite数据库,名字为books.db,该数据库只含有一个表格,名字为books.表格中含有name,isbn,auth ...
- 【转】Pro Android学习笔记(五):了解Content Provider(上)
Content Provider是抽象数据封装和数据访问机制,例如SQLite是Android设备带有的数据源,可以封装到一个content provider中.要通过content provider ...
- udacity android 学习笔记: lesson 4 part a
udacity android 学习笔记: lesson 4 part a 作者:干货店打杂的 /titer1 /Archimedes 出处:https://code.csdn.net/titer1 ...
- Android 学习笔记之Volley(七)实现Json数据加载和解析...
学习内容: 1.使用Volley实现异步加载Json数据... Volley的第二大请求就是通过发送请求异步实现Json数据信息的加载,加载Json数据有两种方式,一种是通过获取Json对象,然后 ...
- Android学习笔记进阶之在图片上涂鸦(能清屏)
Android学习笔记进阶之在图片上涂鸦(能清屏) 2013-11-19 10:52 117人阅读 评论(0) 收藏 举报 HandWritingActivity.java package xiaos ...
随机推荐
- 通过开发MSBuild ,引发的注册表相关知识
最近在做一个小项目,目的就是只需要点一个按钮,就把web程序发布到指定的服务器中.基本步骤就是 编译——>打包->复制包到远程服务器->解压缩.我想重点说一下解压缩,我们可以用win ...
- div排序 根据《input》
jquery代码如下$(function(){//alert($("input").length); var arr=Array(); $("input").e ...
- Codeforces Round #366 (Div. 2) B 猜
B. Spider Man time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...
- ZOJ 1105 FatMouse’s Tour
原题链接 题目大意:FM要去逛街,他可以走任何街道,在任何路口转弯.他走一条陌生街道的速度是20公里每小时,走一条熟悉街道的速度是50公里每小时.输入是街道信息,输出消耗时间. 解法:本质就是浮点运算 ...
- Spring+SpringMVC+Mybatis+ehcache
http://www.tuicool.com/articles/myeANv http://www.mamicode.com/info-detail-1151624.html
- UVa 1225 Digit Counting --- 水题
UVa 1225 题目大意:把前n(n<=10000)个整数顺次写在一起,12345678910111213...,数一数0-9各出现多少字 解题思路:用一个cnt数组记录0-9这10个数字出现 ...
- CSS3卡片旋转效果
HTML: <div id="rotate"> <div id="rotate_wrap"> <div id="fron ...
- PosPal银豹收银系统
http://pospal.cn/pc.html 注册公司的地址,便宜的快法务 http://www.kuaifawu.com/
- (转)Attention
本文转自:http://www.cosmosshadow.com/ml/%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C/2016/03/08/Attention.ht ...
- docker镜像、容器
第一部分:Docker镜像的基本知识 1.1 什么是Docker镜像 从整体的角度来讲,一个完整的Docker镜像可以支撑一个Docker容器的运行,在 Docker容器运行过程中主要提供文件系统视角 ...