数据库 MySQL SQLite 简介 API
目录
SQLite 简介
Android中使用的数据库是开源的、与操作系统无关的SQLite
。
SQLite 第一个Alpha版本诞生于2000年5月,它是一款轻量级数据库,它的设计目标是嵌入式
的,占用资源非常的低,只需要几百K
的内存就够了。
SQLite 已经被多种软件和产品使用,Android、iPhone、Mozilla FireFox 都是使用 SQLite 来存储数据的。
SQLite 数据库是 D.Richard Hipp 用C
语言编写的开源嵌入式数据库,支持的数据库大小为2TB
。
SQLite 的特点
SQLite 具有如下特点:
- 轻量级:SQLite 是
进程内
的数据库引擎,因此不存在数据库的客户端和服务器;使用 SQLite 一般只需要带上它的一个相当小的动态库,就可以享受它的全部功能。 - 独立性:SQLite 数据库的核心引擎本身不依赖第三方软件,使用它也不需要安装。
- 隔离性:SQLite 数据库中的所有信息(比如表、视图、触发器)都包含在一个文件内,方便管理和维护。
- 跨平台:SQLite 数据库支持大部分操作系统,比如Windows、Android、iPhone、Symbian、Palm等。
- 多语言接口:SQLite 数据库支持很多语言编程接口,比如C/C++、Java、Python、dotNet、Ruby、Perl等。
- 安全性:SQLite 数据库通过数据库级上的独占性和共享锁来实现独立事务处理。这意味着多个进程可以在同一时间从同一数据库
读
数据,但只有一个可以写
数据。在某个进程或线程向数据库执行写
操作之前,必须获得独占锁定。在发出独占锁定后,其他的读或写操作将不会再发生。
使用 sqlite3 查看数据库表结构
在 android 中,为某个应用程序创建的数据库文件位于Android设备的 /data/data/包名/databases
文件夹中,并且只有此应用程序自己可以访问,其它应用程序是不能访问的。
开发者若要查看数据库中的内容,方式有两种 :
- 将数据库文件导出后使用可视化工具
SQLite Expert
等软件打开 - 在cmd命令下通过使用系统自带的
sqlite3
命令查看
下面介绍第二种方式,大致步骤为:
- 先通过
adb devices
查看是否有设备连接 - 通过
adb shell
进入手机根目录- 默认情况,只能获取普通用户权限,此时会有一个符号
$
(超管为#
),此时没有访问data
目录的权限 - 若手机已获得了root权限,可以输入
su
或su root
申请root权限,然后在手机上点击授权(如有必要),这样就可以访问/data
目录了
- 默认情况,只能获取普通用户权限,此时会有一个符号
- 定位到指定目录
cd data/data/包名/databases
,查看目录下的文件ls -l
(其中的*.db-journal
为临时文件) - 使用
sqlite3
命令打开数据库文件sqlite3 person.db
,若提示sh: sqlite3: not found
,解决办法见下文 - 执行数据库语句
select * from person;
,注意最后要有一个分号;也可执行其它指令,如.table
查看所有表,.schema
查看所有语句,.help
查看帮助 - 若显示中文时乱码,详见下文
adb devices
adb shell
cd data/data/包名/databases
ls -l
sqlite3 文件名.db
命令行显示中文时乱码解决方案
- 重新开启CMD窗口,输入:
chcp 65001
回车 - 在命令行标题栏上点击右键,选择属性 -- 字体,将字体修改为
Lucida Console
(默认为点阵字体),确定 - 完成后再通过命令进入 sqlite3,select 一下含有中文的记录,乱码就解决了
PS:
65001
是指使用UTF-8
的编码,GB2312
为936
,可以从 EditPlus 工具的菜单--文档--文档类型 查看
sqlite3:not found 解决方法
sqlite3 为一个可执行脚本程序,在system/xbin/
下面,某些品牌手机 rom 不带这个东西,导致使用该工具出现 sqlite3:not found
错误,下面就详细讲解如何解决此问题。
注意:
- sqlite3 一般情况下都是通用的,所以随便去找个 sqlite3 就好,或者使用相应版本的模拟器中的
/system/xbin
目录下的 sqlite3 也可以 - ARM 机器上不能使用 x86 模拟器上的 sqlite3
- 若缺少
libncurses.so
文件,会报libncurses.so not found
错误,处理方式是一样的,建议同时导入这两个文件
完整步骤
# 获取 root 权限
adb devices
adb shell
su
# 让 /system 文件夹可读写
mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
# 从模拟器的 /system/xbin 中导出 sqlite3 文件,从 /system/lib 中导出 libncurses.so 文件,将上面导出的文件导入到真机的 sdcard 中
# 将 sdcard 中的文件复制到手机系统相应目录中
cd /
cat /sdcard/sqlite3 > /system/xbin/sqlite3
cat /sdcard/libncurses.so > /system/lib/libncurses.so
# 修改文件权限
chmod 4755 /system/xbin/sqlite3
chmod 4755 /system/lib/libncurses.so
# 设置 /system为只读文件
mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system
MySQL 简介
MySQL 是最流行的关系型数据库管理系统
(Relational Database Management System, RDBMS),在 WEB 应用方面 MySQL 是最好的 RDBMS 应用软件之一。
简介
什么是数据库
数据库(Database)是按照数据结构来组织、存储和管理数据的仓库。
每个数据库都有一个或多个不同的 API 用于创建,访问,管理,搜索和复制所保存的数据。
我们也可以将数据存储在文件中,但是在文件中读写数据速度
相对较慢。
所以,现在我们使用关系型数据库管理系统来存储和管理大数据量。所谓的关系型数据库,是建立在关系模型
基础上的数据库,借助于集合代数等数学概念和方法来处理数据库中的数据。
关系数据库管理系统的特点:
- 数据以
表格
的形式出现 - 每
行
为各种记录名称 - 每
列
为记录名称所对应的数据域 - 许多的行和列组成一张表单
- 若干的表单组成database
术语
在我们开始学习 MySQL 数据库前,让我们先了解下 RDBMS 的一些术语:
- 数据库: 数据库是一些关联表的集合。
- 数据表: 表是数据的矩阵。在一个数据库中的表看起来像一个简单的电子表格。
- 列: 一列(数据元素) 包含了相同类型的数据, 例如邮政编码的数据。
- 行:一行(=元组,或记录)是一组相关的数据,例如一条用户订阅的数据。
- 冗余:存储两倍数据,冗余降低了性能,但提高了数据的安全性。
- 主键:主键是唯一的。一个数据表中只能包含一个主键。你可以使用主键来查询数据。
- 外键:外键用于关联两个表。
- 索引:使用索引可快速访问数据库表中的特定信息。索引是对数据库表中一列或多列的值进行排序的一种结构。类似于书籍的目录。
- 复合键:复合键(组合键)将多个列作为一个索引键,一般用于复合索引。
- 参照完整性: 参照的完整性要求关系中不允许引用不存在的实体。与实体完整性是关系模型必须满足的完整性约束条件,目的是保证数据的一致性。
MySQL 为关系型数据库, 这种所谓的"关系型"可以理解为"表格"的概念, 一个关系型数据库由一个或数个表格组成:
- 表头(header): 每一列的名称;
- 列(col): 具有相同数据类型的数据的集合;
- 行(row): 每一行用来描述某条记录的具体信息;
- 值(value): 行的具体信息, 每个值必须与该列的数据类型相同;
- 键(key): 键的值在当前列中具有唯一性。
MySQL 特点
MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司
。MySQL 是一种关联数据库管理系统,关联数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。
- MySQL 是开源的,所以你不需要支付额外的费用。
- MySQL 支持大型的数据库。可以处理拥有
上千万条记录
的大型数据库。 - MySQL 使用标准的 SQL 数据语言形式。
- MySQL 可以运行于多个系统上,并且支持多种语言。这些编程语言包括 C、C++、Python、Java、Perl、PHP、Eiffel、Ruby 和 Tcl 等。
- MySQL 对PHP有很好的支持,PHP 是目前最流行的 Web 开发语言。
- MySQL 支持大型数据库,支持 5000 万条记录的数据仓库,32 位系统表文件最大可支持 4GB,64 位系统支持最大的表文件为8TB。
- MySQL 是可以定制的,采用了 GPL 协议,你可以修改源码来开发自己的 MySQL 系统。
MariaDB
MariaDB 数据库管理系统是 MySQL 的一个分支,主要由开源社区在维护,采用 GPL 授权许可。MariaDB 的目的是完全兼容 MySQL,包括 API 和命令行,使之能轻松成为 MySQL 的代替品。
MariaDB 由 MySQL 的创始人Michael Widenius
主导开发,他早前曾以10亿美元的价格,将自己创建的公司MySQL AB
卖给了SUN
,此后,随着SUN被Oracle
收购,MySQL 的所有权也落入 Oracle 的手中。
开发这个分支的原因之一是:甲骨文公司收购了 MySQL 后,有将 MySQL 闭源的潜在风险,因此社区采用分支的方式来避开这个风险。 过去一年中,大型互联网用户以及 Linux 发行商纷纷抛弃 MySQL,转投 MariaDB 阵营。MariaDB 是目前最受关注的 MySQL 数据库衍生版,也被视为开源数据库 MySQL 的替代品。
MariaDB 名称来自 Michael Widenius 的女儿 Maria 的名字。
MySQL 安装及配置
可以在 MySQL官网 中下载,最新版本下载地址:mysql-8.0.21-winx64.zip
配置文件
\下载完后,我们将 zip 包解压到相应的目录
打开刚刚解压的文件夹,在该文件夹下创建 my.ini 配置文件,配置以下基本信息:
[client]
# 设置mysql客户端默认字符集
default-character-set=utf8
[mysqld]
# 设置端口号
port = 3306
# 设置mysql的安装目录,注意目录分割符要用\\
basedir=D:\\software\\mysql-8.0.21-winx64
# 设置 mysql数据库的数据的存放目录
datadir=D:\\_test\\_mysql\\_data
# 允许最大连接数
max_connections=20
# 服务端使用的字符集
character-set-server=utf8
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
环境变量
打开 Windows 环境变量设置, 新建变量名 MYSQL_HOME
, 变量值为 MySQL 安装目录路径,例如D:\software\mysql-8.0.21-winx64
在 环境变量 的 Path
变量中添加%MYSQL_HOME%\bin
通过以下命令查看版本号,如果正确输出表示配置成功:
mysql -V
mysql --help | grep Ver
D:\software\mysql-8.0.21-winx64\bin\mysql.exe Ver 8.0.21 for Win64 on x86_64 (MySQL Community Server - GPL)
在登录 MySQL 后,还可以通过如下命令查看版本信息:
select version();
status;
初始化 MySQL
以管理员
身份打开 cmd 命令行工具,初始化数据库:
mysqld --initialize --console
执行完成后,会输出 root 用户的初始默认密码,如:
2020-10-07T08:38:04.455187Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: <FyNCj5KDasx
注意:里面的
<FyNCj5KDasx
就是初始密码,后续登录需要用到。
输入以下安装命令:
mysqld install
如果提示
Install of the Service Denied
,是因为cmd没有用管理员
身份打开导致没有权限
初始化 data 目录:
mysqld --initialize-insecure
启动及关闭 MySQL 服务
输入以下命令即可启动 MySQL 服务:
net start mysql
//或 mysqld --console
注意 cmd 命令窗口必须以管理员身份打开
关闭 MySQL 服务:
net stop mysql
//或 mysqladmin -uroot shudown
查看本地 MySQL 服务是否启动:
netstat -an|find "3306"
卸载 MySQL
sc delete MySQL
用这几个命令就可以快速、完全的关闭 MySQL 服务了,不需要网上那么多杂七杂八的步骤
备份与恢复
备份数据库
备份前先退出数据库,回到CMD窗口下
quit
mysqldump -u userName -p dbName > fileName
mysqldump -u root -p dbName > c:/test.sql
恢复数据库
恢复数据只能恢复数据本身
,原先的数据库(名)没法恢复,所以恢复前需要先自己创建出数据库。
恢复方式1:在cmd窗口下
mysql -u root -p dbName < c:/test.sql
恢复方式2:在mysql命令下
use newDBName;
source c:/newDBName.sql
登录 MySQL
当 MySQL 服务已经运行时,我们可以通过如下命令登录到 MySQL 数据库中:
mysql [-h 主机名] -u 用户名 -p
参数说明:
- -h : 指定客户端所要登录的 MySQL 主机名,登录本机(localhost 或 127.0.0.1)该参数可以省略
- -u : 登录的用户名
- -p : 告诉服务器将会使用一个密码来登录,如果所要登录的用户名密码为空,可以忽略此选项
如果我们要登录本机的 MySQL 数据库,只需要输入以下命令即可:
mysql -u root -p
按回车确认,如果安装正确且 MySQL 正在运行,会提示你Enter password
若密码存在则输入密码登录,不存在则直接按回车登录。登录成功后你将会看到 Welcome to the MySQL monitor... 的提示语。
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.21
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
然后命令提示符会一直以 mysq>
加一个闪烁的光标等待命令的输入,输入 exit 或 quit 退出登录。
修改初始密码
登录后会发现,输入任何命令均提示:
ERROR 1820 (HY000): You must reset your password using ALTER USER statement
before executing this statement.
所以需要重置密码:
alter user 'root'@'localhost' identified by '123';
这样,密码就被改成了 123
用户设置
我们创建的 MySQL 用户的信息,其实都保存在名称为mysql
的 database 中。
显示所有的 database:
show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
选择名为mysql
的 database:
use mysql;
显示mysql
database 的所有表,可以看到其中有个user
表:
show tables;
+---------------------------+
| Tables_in_mysql |
+---------------------------+
| ... |
| user |
+---------------------------+
显示user
表结构:
desc user;
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host | char(255) | NO | PRI | | |
| User | char(32) | NO | PRI | | |
| authentication_string | text | YES | | NULL | |
| password_last_changed | timestamp | YES | | NULL | |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
查看当前所有 MySQL 用户的 username、host、密码(还有很多用户授权、锁定、过期等信息可以查看):
select User,Host,authentication_string from user;
+------------------+-----------+------------------------------------------------------------------------+
| User | Host | authentication_string |
+------------------+-----------+------------------------------------------------------------------------+
| mysql.infoschema | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.session | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.sys | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| root | localhost | $A$005$∟☺"E^*uvO↕☺W<↑BIIiV/Z4LsByE9PebHl5MXE4USvQFCthUxDwt.R6V.4uO7 |
+------------------+-----------+------------------------------------------------------------------------+
获取的密码是经 SHA1 加密的
如果你需要添加 MySQL 用户,你只需要在 mysql 数据库中的 user 表添加新用户即可。
API 文档
SQLiteOpenHelper 文档
A helper class to manage database creation
and version management
.
You create a subclass implementing onCreate(SQLiteDatabase)
, onUpgrade(SQLiteDatabase, int, int)
and optionally onOpen(SQLiteDatabase)
, and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions 事务 are used to make sure the database is always in a sensible state.
This class makes it easy for ContentProvider
implementations to defer 推迟 opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.
Note: this class assumes monotonically 单调 increasing version numbers for upgrades.
构造方法
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version)
Create a helper object to create, open, and/or manage a database. This method always returns very quickly. The database is not actually created or opened until one of getWritableDatabase()
or getReadableDatabase()
is called.
- context Context: to use for locating paths to the the database. This value may be null.
- name String: of the database file, or null for an
in-memory
database. This value may be null. - factory SQLiteDatabase.CursorFactory: to use for creating cursor objects, or null for the default. This value may be null.
- version int: number of the database (starting at 1); if the database is older,
onUpgrade
will be used to upgrade the database; if the database is newer,onDowngrade
will be used to downgrade the database
onCreate
public abstract void onCreate (SQLiteDatabase db)
Called when the database is created for the first time. This is where the creation of tables and the initial population 填充 of the tables should happen.
onUpgrade
public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.
The SQLite ALTER TABLE documentation can be found here. If you add new columns
you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
you can use ALTER TABLE to rename the old table, then create the new table and then populate 填充 the new table with the contents of the old table.
This method executes within a transaction. If an exception is thrown, all changes will automatically be rolled back.
Parameters
- db SQLiteDatabase: The database.
- oldVersion int: The old database version.
- newVersion int: The new database version.
onDowngrade
public void onDowngrade (SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be downgraded. This is strictly similar to onUpgrade
method, but is called whenever current version is newer than requested one. However, this method is not abstract, so it is not mandatory 强制性的 for a customer to implement it. If not overridden, default implementation will reject 拒绝 downgrade and throws SQLiteException
This method executes within a transaction. If an exception is thrown, all changes will automatically be rolled back.
onOpen
public void onOpen (SQLiteDatabase db)
Called when the database has been opened. The implementation should check SQLiteDatabase#isReadOnly
before updating the database.
This method is called after the database connection
has been configured and after the database schema
has been created, upgraded or downgraded as necessary. If the database connection must be configured in some way before the schema is created, upgraded, or downgraded, do it in onConfigure
instead.
onConfigure
public void onConfigure (SQLiteDatabase db)
Called when the database connection is being configured, to enable features such as write-ahead logging
or foreign key
support.
This method is called before onCreate, onUpgrade, onDowngrade, or onOpen are called. It should not modify the database except to configure the database connection as required.
This method should only call methods that configure the parameters of the database connection, such as enableWriteAheadLogging、setForeignKeyConstraintsEnabled、setLocale、setMaximumSize, or executing PRAGMA statements.
getWritableDatabase
public SQLiteDatabase getWritableDatabase ()
Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and onCreate
, onUpgrade
and/or onOpen
will be called.
Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call close()
when you no longer need the database.)
Errors such as bad permissions or a full disk may cause this method to fail, but future attempts may succeed if the problem is fixed.
Database upgrade may take a long time, you should not call this method from the application main thread, including from
ContentProvider.onCreate()
.
Returns a read/write
database object valid until close()
is called
getReadableDatabase
public SQLiteDatabase getReadableDatabase ()
Create and/or open a database. This will be the same object returned by getWritableDatabase()
unless some problem, such as a full disk 磁盘已满, requires the database to be opened read-only
. In that case, a read-only
database object will be returned. If the problem is fixed, a future call to getWritableDatabase()
may succeed, in which case the read-only
database object will be closed and the read/write
object will be returned in the future.
Like
getWritableDatabase()
, this method may take a long time to return, so you should not call it from the application main thread, including fromContentProvider.onCreate()
.
Returns a database object valid until getWritableDatabase()
or close()
is called.
SQLiteDatabase 文档
SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.
Database names must be unique within an application, not across all applications.
Localized Collation 整理 - ORDER BY
In addition to SQLite's default
BINARY
collator, Android supplies two more,LOCALIZED
, which changes with the system's current locale, andUNICODE
, which is the Unicode Collation Algorithm and not tailored 适合 to the current locale.
beginTransaction
public void beginTransaction ()
Begins a transaction in EXCLUSIVE mode 独占模式.
Transactions can be nested 嵌套. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful
). Otherwise they will be committed.
Here is the standard idiom 标准用法 for transactions:
db.beginTransaction();
try {
//...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
execSQL
public void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
It has no means to return any data (such as the number of affected rows). Instead, you're encouraged 鼓励 to use insert、 update, et al, when possible.
Parameters sql String: the SQL statement to be executed. Multiple statements separated by semicolons are not supported.
insert
public long insert (String table, String nullColumnHack, ContentValues values)
public long insertOrThrow (String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
Parameters
- table String: the table to insert the row into
- nullColumnHack String: optional, may be
null
.- 这个参数传
null
就行了,一般没啥用 - SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted.
- If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly 显式 insert a NULL into in the case where your values is empty.
- 这个参数传
- values ContentValues: this
map
contains the initial column values for the row. Thekeys
should be the column names and thevalues
the column values
Returns the row ID of the newly inserted row, or -1
if an error occurred
delete
public int delete (String table, String whereClause, String[] whereArgs)
Convenience method for deleting rows in the database.
Parameters
- table String: the table to delete from
- whereClause String: the optional WHERE clause to apply when deleting.
Passing null will delete all rows.
- whereArgs String: You may include
?s
in the where clause, which will be replaced by the values from whereArgs. The values will be bound 绑定 as Strings.
Returns the number of rows affected if a whereClause is passed in, 0
otherwise. To remove all rows and get a count pass "1"
as the whereClause.
update
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Convenience method for updating rows in the database.
Parameters
- table String: the table to update in
- values ContentValues: a
map
from column names to new column values.null
is a valid value that will be translated 转换为 toNULL
. - whereClause String: the optional WHERE clause to apply when updating.
Passing null will update all rows.
- whereArgs String: You may include
?s
in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings.
Returns the number of rows affected
query
public Cursor query (boolean distinct, String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a Cursor
over the result set.
Parameters
- distinct boolean: true if you want each row to be unique, false otherwise.
- table String: The table name to compile the query against.
- columns String: A list of which columns to return.
- Passing
null
will return all columns, which is discouraged 不建议 to prevent 防止 reading data from storage that isn't going to be used.
- Passing
- selection String: A filter declaring 声明 which rows to return, formatted as 格式为 an SQL WHERE clause 字句.
- Passing
null
will return all rows for the given table.
- Passing
- selectionArgs String: You may include
?s
in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings. - groupBy String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause.
- Passing
null
will cause the rows to not be grouped.
- Passing
- having String: A filter declare which
row groups
to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause.- Passing
null
will cause all row groups to be included, and is required 需要 when row grouping is not being used.
- Passing
- orderBy String: How to order the rows, formatted as an SQL ORDER BY clause.
- Passing
null
will use the default sort order, which may be unordered.
- Passing
- limit String: Limits the number of rows returned by the query, formatted as LIMIT clause.
- Passing
null
denotes 表示 no LIMIT clause.
- Passing
Returns A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
Cursor 文档
This interface provides random read-write access
to the result set returned by a database query
.
Cursor implementations are not required to be synchronized
so code using a Cursor from multiple threads should perform its own synchronization when using the Cursor.
Implementations should subclass AbstractCursor.
close
public abstract void close ()
Closes the Cursor, releasing all of its resources and making it completely invalid.
getColumnIndex
public abstract int getColumnIndex (String columnName)
public abstract int getColumnIndexOrThrow (String columnName)
Returns the zero-based
index for the given column name, or -1
if the column doesn't exist. If you expect the column to exist use getColumnIndexOrThrow
instead, which will make the error more clear.
- Parameters columnName String: the name of the target column.
- Returns the zero-based column index for the given column name, or -1 if the column name does not exist.
getColumnName
public abstract String getColumnName (int columnIndex)
Returns the column name at the given zero-based column index.
getType
public abstract int getType (int columnIndex)
Returns data type of the given column's value. The preferred type 首选类型 of the column is returned but the data may be converted to other types as documented in the get-type methods such as getInt(int), getFloat(int) etc.
Returned column types are
- FIELD_TYPE_NULL
- FIELD_TYPE_INTEGER
- FIELD_TYPE_FLOAT
- FIELD_TYPE_STRING
- FIELD_TYPE_BLOB
getInt...
public abstract int getInt (int columnIndex)
public abstract double getDouble (int columnIndex)
public abstract float getFloat (int columnIndex)
public abstract long getLong (int columnIndex)
public abstract short getShort (int columnIndex)
public abstract String getString (int columnIndex)
Returns the value of the requested column as an int.
The result and whether this method throws an exception when the column value is null, the column type is not an integral type, or the integer value is outside the range [Integer.MIN_VALUE, Integer.MAX_VALUE] is implementation-defined 由各个实现定义.
- Parameters columnIndex int: the zero-based index of the target column.
- Returns: the value of that column as an int.
moveTo...
public abstract boolean moveToNext ()
public abstract boolean moveToPrevious ()
Move the cursor to the next/previous row.
This method will return false if the cursor is already past the last
/ before the first
entry in the result set.
Returns: whether the move succeeded.
public abstract boolean moveToFirst ()
public abstract boolean moveToLast ()
Move the cursor to the first/last row.
This method will return false if the cursor is empty.
public abstract boolean moveToPosition (int position)
Move the cursor to an absolute position. The valid range of values is -1 <= position <= count
.
This method will return true if the request destination was reachable, otherwise, it returns false.
ContentValues 文档
This class is used to store a set
of values that the ContentResolver
can process.
构造方法
public ContentValues ()
public ContentValues (int size)
public ContentValues (ContentValues from)
Creates an empty set of values using the default/given
initial size
Creates a set of values copied from the given set
put
void put(String key, Short value)
void put(String key, Long value)
void put(String key, Double value)
void put(String key, Integer value)
void put(String key, String value)
void put(String key, Boolean value)
void put(String key, Float value)
void put(String key, byte[] value)
void put(String key, Byte value)
void putAll(ContentValues other)
void putNull(String key)
get
Object get(String key)
Boolean getAsBoolean(String key)
Byte getAsByte(String key)
byte[] getAsByteArray(String key)
Double getAsDouble(String key)
Float getAsFloat(String key)
Integer getAsInteger(String key)
Long getAsLong(String key)
Short getAsShort(String key)
String getAsString(String key)
其他方法
public void clear ()
public boolean containsKey (String key)
public boolean isEmpty ()
public Set<String> keySet ()
public void remove (String key)
public int size ()
public Set<Entry<String, Object>> valueSet ()
2016-04-14
本文来自博客园,作者:白乾涛,转载请注明原文链接:https://www.cnblogs.com/baiqiantao/p/5389463.html