Android中的数据库——SQLite
2015-10-12 14:11
405 查看
SQLite是遵守ACID的关系型数据库管理系统。
废话不多说,直接上代码。
<span style="white-space:pre"> </span>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//打开或创建test.db数据库
SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
db.execSQL("DROP TABLE IF EXISTS person");
//创建person表
db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
Person person = new Person();
person.name = "Daniel";
person.age = 1;
person.name = "Spark";
person.age = 33;
//ContentValues以键值对的形式存放数据
ContentValues cv = new ContentValues();
cv.put("name", person.name);
cv.put("age", person.age);
//插入ContentValues中的数据
db.insert("person", null, cv);
cv = new ContentValues();
cv.put("age", 2);
//更新数据
db.update("person", cv, "name = ?", new String[]{"john"});
Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"3"});
while (c.moveToNext()) {
int _id = c.getInt(c.getColumnIndex("_id"));
String name = c.getString(c.getColumnIndex("name"));
int age = c.getInt(c.getColumnIndex("age"));
Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age);
}
c.close();
//删除数据
db.delete("person", "age < ?", new String[]{"5"});
//关闭数据库
db.close();
//删除数据库
//deleteDatabase("test.db");
}
几个函数的说明:
Added in API level 1
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的时候使用这个函数。
Added in API level 1
Convenience method for inserting a row into the database.
Parameters
Returns
the row ID of the newly inserted row, or -1 if an error occurred
Added in API level 1
Convenience method for updating rows in the database.
Parameters
Returns
the number of rows affected
Added in API level 1
Query the given URL, returning a
the result set.
Parameters
Returns
A
which is positioned before the first entry. Note that
are not synchronized, see the documentation for more details.
See Also
注意:
执行完操作后,一定不要忘记cursor.close()和database.close()。一定不要忘记cursor.close()和database.close()。一定不要忘记cursor.close()和database.close()。
重要的事说三遍!
废话不多说,直接上代码。
<span style="white-space:pre"> </span>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//打开或创建test.db数据库
SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
db.execSQL("DROP TABLE IF EXISTS person");
//创建person表
db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
Person person = new Person();
person.name = "Daniel";
person.age = 1;
person.name = "Spark";
person.age = 33;
//ContentValues以键值对的形式存放数据
ContentValues cv = new ContentValues();
cv.put("name", person.name);
cv.put("age", person.age);
//插入ContentValues中的数据
db.insert("person", null, cv);
cv = new ContentValues();
cv.put("age", 2);
//更新数据
db.update("person", cv, "name = ?", new String[]{"john"});
Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"3"});
while (c.moveToNext()) {
int _id = c.getInt(c.getColumnIndex("_id"));
String name = c.getString(c.getColumnIndex("name"));
int age = c.getInt(c.getColumnIndex("age"));
Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age);
}
c.close();
//删除数据
db.delete("person", "age < ?", new String[]{"5"});
//关闭数据库
db.close();
//删除数据库
//deleteDatabase("test.db");
}
几个函数的说明:
public void execSQL (String sql)
Added in API level 1Execute 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(String, String, ContentValues),
update(String, ContentValues, String, String[]), et al, when possible.
因为没有返回值,所以不要在insert,update的时候使用这个函数。
public long insert (String table, String nullColumnHack, ContentValues values)
Added in API level 1Convenience method for inserting a row into the database.
Parameters
table | the table to insert the row into |
---|---|
nullColumnHack | optional; may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided valuesis empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHackparameter provides the name of nullable column name to explicitly insert a NULL into in the case where your valuesis empty. |
values | this map contains the initial column values for the row. The keys should be the column names and the values the column values |
the row ID of the newly inserted row, or -1 if an error occurred
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Added in API level 1Convenience method for updating rows in the database.
Parameters
table | the table to update in |
---|---|
values | a map from column names to new column values. null is a valid value that will be translated to NULL. |
whereClause | the optional WHERE clause to apply when updating. Passing null will update all rows. |
whereArgs | You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. |
the number of rows affected
public Cursor query (boolean
distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Added in API level 1Query the given URL, returning a
Cursorover
the result set.
Parameters
distinct | true if you want each row to be unique, false otherwise. |
---|---|
table | The table name to compile the query against. |
columns | 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. |
selection | A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table. |
selectionArgs | 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 | A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. |
having | A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. |
orderBy | How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. |
limit | Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause. |
A
Cursorobject,
which is positioned before the first entry. Note that
Cursors
are not synchronized, see the documentation for more details.
See Also
Cursor
注意:
执行完操作后,一定不要忘记cursor.close()和database.close()。一定不要忘记cursor.close()和database.close()。一定不要忘记cursor.close()和database.close()。
重要的事说三遍!
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析