得到了数据库的对象,接着就是对数据库进行操作。增删改查。我们就需要查看SQLiteDatabase
数据库操作的一些方法
下面就是我从文档中摘取的一些方法:
| 返回值 | 方法 | 说明 |
| void | execSQL(String sql) | Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data. |
| void | execSQL(String sql, Object[] bindArgs) | Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. |
| int | getVersion() | Gets the database version. |
| long | insert(String table, String nullColumnHack, ContentValues values) | Convenience method for inserting a row into the database. |
| boolean | isReadOnly() | Returns true if the database is opened as read only. |
| boolean | isOpen() | Returns true if the database is currently open. |
| 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. |
| Cursor | query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) | Query the given table, returning a Cursor over the result set. |
| Cursor | query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal) | Query the given URL, returning a Cursor over the result set. |
| Cursor | query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) | Query the given table, returning a Cursor over the result set. |
| int | update(String table, ContentValues values, String whereClause, String[] whereArgs) | Convenience method for updating rows in the database. |
插入数据
insert的SQL语句
不妨看看SQL语句是如何进行插入数据的:
insert into TABLE_NAME values(value1, value2, value3, value4);
insert into TABLE_NAME(ParameterName1,ParameterName2, ParameterName3) values (value1, value2, value3);
故而如果在程序中指定,由于不确定那些参数是默认不写,故而需要指定表中列名+对应的值。
插入数据,我们就要先看ContentValues
ContentValues
用来存储值得序列,先看构造函数:ContentValues() Creates an empty set of values using the default initial size 用默认大小的存储创建一个空的值集合。ContentValues(int size) Creates an empty set of values using the given initial size 用指定大小的size存储创建一个空值集合。
既然是集合,我们就需要了解如何存储值:
| void | put(String key, Short value) | Adds a value to the set |
| void | put(String key, Long value) | Adds a value to the set |
| void | put(String key, Double value) | Adds a value to the set |
| void | put(String key, Integer value) | Adds a value to the set |
| void | put(String key, String value) | Adds a value to the set |
| void | put(String key, Boolean value) | Adds a value to the set |
| void | put(String key, Float value) | Adds a value to the set |
| void | put(String key, byte[] value) | Adds a value to the set |
| void | put(String key, Byte value) | Adds a value to the set |
| void | putNull(String key) | Adds a null value to the set. |
| void | remove(String key) | Remove a single value. |
| int | size() | Returns the number of values. |
| Object | get(String key) | Gets a value. |
| void | clear() | Removes all values. |
| boolean | containsKey(String key) | Returns true if this object has the named value. |
几乎和Map集合一样,接着就进行简单的数据插入操作:
这里还是使用前一讲的DatabaseHelper.java类,在MainActivity.java中完成数据插入的操作。
在布局文件中新增一个按钮insert,然后添加监听,在监听函数中,写入插入数据的代码:
insert = (Button)findViewById(R.id.insert);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
DatabaseHelper helper = new DatabaseHelper(MainActivity.this, "weizu", null, 1);
//Create and/or open a database.创建过了,调用就是打开open
//"create table weizu(id int, name varchar(20), age int)"
SQLiteDatabase db = helper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("id", 1);
values.put("name", "无涯明月");
values.put("age", 24);
db.insert("weizu", null, values);
}
});
同样的,还是使用CMD窗口,我们查看我们的数据库中是否有我们插入的数据:
使用命令:select * form weizu;
控制台窗口的编码是GBK,数据库编码应该是UTF-8,出现了乱码。不过可见插入数据成功。
更新数据
update的SQL语句
不妨看看SQL语句是如何进行数据更新的:
update TABLE_NAME set ParameterName1 = value1 where ParameterName2 = value2
update TABLE_NAME set ParameterName1 = value1,ParameterName2 = value2 where ParameterName3 = value3
在java操作数据库的时候,我们都知道可以使用?占位符,然后在后面确定值,这里也同样。
update的原型:
public int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
看看参数的解释:
| 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 to NULL. |
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. |
上面的参数说明也告知了可以使用?占位符在whereClause中,然后在whereArgs中填值。而values也就是新的列值。下面就来个案例操作一下:
当然,还是在上面的案例的基础上,我们修改年龄为50。
同样的新增一个按钮update,然后添加事件监听:
update = (Button)findViewById(R.id.update);
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
DatabaseHelper helper = new DatabaseHelper(MainActivity.this, "weizu", null, 1);
SQLiteDatabase db = helper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("age", 50);
db.update("weizu", values, "id=?",new String[]{"1"});
}
});
效果,居然是两行,说明实际上原本的数据库没有随着重新安装程序删除掉。如下图:
查询数据
query的SQL语句
不妨看看SQL语句是如何进行数据更新的:原文
SELECT select_list
FROM table_name
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
[limit m,n]
如:select classNo from table_name group by classNo having(avg(成绩)>70) order by classNo limit 0,10limit 0,10是从第一条开始,取10条数据
where后跟条件用来筛选我们所需的行。它后面可以跟的操作符有=、!=、<、>、<=、>=、in、like(可以和通配符%结合一起用,效果将会更好) 、between....and.......、AND、OR、NOTgroup by(GROUP BY语句用于结合合计函数(也叫聚合函数sumcountavgmaxmin),根据一个或多个列对结果集进行分组。否则没有多大的意义)group by有一个原则,就是select后面的所有列中,没有使用聚合函数的列,必须出现在group by后面
如果你使用了group by,而没有相应的使用聚合函数那么结果就没有意义了having这个是针对查询的结果进行作用,只能对结果拥有的列进行操作,与where不同的是where是针对原表(就是from后面的那张表的字段)发挥作用。其中having里面可以使用聚合函数。为group by子句设置条件,类似于where为select语句设置条件的方法。having的查找条件可以包括集合函数表达式。除此之外,它的查找条件与where查找条件相同。
看query原型:
public Cursor query (boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
参数:
| 参数 | |
|---|---|
distinct |
boolean:如果您希望每一行都是唯一的,则为true,否则为false。 |
table |
String:用于查询的表名。 |
columns |
String:要查询的列的列名。传递null将返回所有列,相当于 select语句 select关键字后面部分 |
selection |
String:一个过滤器,声明要返回哪些行,格式化为SQL WHERE子句(不包括WHERE本身)。传递null将返回给定表的所有行。在条件子句中允许使用占位符。 |
selectionArgs |
String:您可以在selection中包含?,它将被selectionArgs中的值替换,以便它们出现在selection中。这些值将绑定为字符串。 |
groupBy |
String:一个过滤器,声明如何对行进行分组,格式化为SQL GROUP BY子句(不包括GROUP BY本身)。传递null将导致行不被分组。 |
having |
String:过滤器声明要在游标中包含哪些行组,如果正在使用行分组,则格式化为SQL HAVING子句(不包括HAVING本身)。传递null将导致包含所有行组,并且在未使用行分组时是必需的。 |
orderBy |
String:如何对行进行排序,格式化为SQL ORDER BY子句(不包括ORDER BY本身)。传递null将使用默认排序顺序,该顺序可能是无序的。 |
limit |
String:限制查询返回的行数,用于进行分页,格式为LIMIT子句。传递null表示没有LIMIT子句。 |
Cursor
是一个接口,该接口提供对数据库查询结果集的随机读写权限。下面还是摘取部分的方法:
| int | getColumnCount() | 返回总列数。 |
| int | getColumnIndex(String columnName) | 返回给定列名的从零开始的索引,如果该列不存在,则返回-1。 |
| String | getColumnName(int columnIndex) | 返回给定的从零开始的列索引处的列名称。 |
| String[] | getColumnNames() | 返回一个字符串数组,其中包含结果集中所有列的名称,按其在结果中列出的顺序排列。 |
| int | getCount() | 返回游标中的行数。 |
| Bundle | getExtras() | 返回一组额外值。 |
| byte[] | getBlob(int columnIndex) | 以字节数组的形式返回请求列的值。 |
| double | getDouble(int columnIndex) | 以double形式返回请求列的值。 |
| float | getFloat(int columnIndex) | 以float形式返回请求列的值。 |
| long | getLong(int columnIndex) | 以long形式返回请求列的值。 |
| int | getPosition() | 返回行集中光标的当前位置。 |
| short | getShort(int columnIndex) | 以short形式返回请求列的值。 |
| String | getString(int columnIndex) | 以String形式返回所请求列的值。 |
| int | getType(int columnIndex) | 返回给定列的值的数据类型。 |
| boolean | isAfterLast() | 返回光标是否指向最后一行之后的位置。 |
| boolean | isBeforeFirst() | 返回光标是否指向第一行之前的位置。 |
| boolean | isClosed() | 如果光标关闭则返回true |
| boolean | isFirst() | 返回光标是否指向第一行。 |
| boolean | isLast() | 返回光标是否指向最后一行。 |
| boolean | isNull(int columnIndex) | true如果指示列中的值为null,则返回。 |
| boolean | move(int offset) | 将光标从当前位置向前或向后移动相对量。 |
| boolean | moveToFirst() | 将光标移动到第一行。 |
| boolean | moveToLast() | 将光标移动到最后一行。 |
| boolean | moveToNext() | 将光标移动到下一行。 |
| boolean | moveToPosition(int position) | 将光标移动到绝对位置。 |
| boolean | moveToPrevious() | 将光标移动到上一行。 |
案例:
还是加一个按钮,然后下面是MainActivity.java中新增的代码:
query = (Button)findViewById(R.id.query);
query.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
DatabaseHelper helper = new DatabaseHelper(MainActivity.this, "weizu", null, 1);
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(false, "weizu", new String[]{"id", "name", "age"}, "id=?", new String[]{"1"}, null, null, null, null);
while(cursor.moveToNext()){
int _id = cursor.getInt(cursor.getColumnIndex("id"));
String _name = cursor.getString(cursor.getColumnIndex("name"));
int _age = cursor.getInt(cursor.getColumnIndex("age"));
Toast.makeText(MainActivity.this, "id=" + _id + "|name=" + _name + "|age=" + _age, 20).show();
}
}
});
效果: