2、SQLite数据库相关操作方法
对SQLite数据库的操作一般包括:创建一个数据库,打开数据库,关闭数据库,删除数据库。
2.1、创建和打开数据库的方法:
使用openOrCreateDatabase()方法来创建,若数据库不存在,则会创建新数据库,若存在,则打开数据库。和openFileOutput(String filename,mode)的使用差不多,请参看这篇博文,http://blog.csdn.net/conowen/article/details/7296121
openOrCreateDatabase()方法的返回值为一个SQLiteDatabase对象。详细可以参看以下openOrCreateDatabase()方法的官方说明
public SQLiteDatabase openOrCreateDatabase (String name, int mode, SQLiteDatabase.CursorFactory factory)
Open a new private SQLiteDatabase associated with this Context's application package. Create the database file if it doesn't exist.
Parameters
name | The name (unique in the application package) of the database. |
---|---|
mode | Operating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_WORLD_READABLE andMODE_WORLD_WRITEABLE to control permissions. |
factory | An optional factory class that is called to instantiate a cursor when query is called. |
Returns
- The contents of a newly created database with the given name.
第一个参数————为数据库的名字,string类型。
第二个参数————为常量,如下所示
常量 含义
MODE_PRIVATE
默认模式,值为0,文件只可以被调用该方法的应用程序访问
MODE_WORLD_READABLE
所有的应用程序都具有对该文件读的权限。
MODE_WORLD_WRITEABLE
所有的应用程序都具有对该文件写的权限。
第三个参数————当query方法被调用时,用来实例化cursor,通常为null
2.2、关闭SQLite数据库
对数据库操作完毕之后,就要关闭数据库,否则会抛出SQLiteException异常。关闭数据库只需调用成SQLiteDatabase对象的.close()方法即可。
2.3、删除数据库
直接调用deleteDatebase()方法即可,如:
- this.deleteDatabase("mysqlite.db")
3、SQLite数据库中(Table )“表”的操作方法
首先要明确一点的是,一个数据库可以有很多表,一个表中包含很多条数据,也就是说,在数据库里面保存数据其实是保存在Table (表)里面的。对已经存在和已经创建的数据库操作一般包括:创建表,往表添加数据,从表中删除数据,修改表中的数据,查询表中的数据,删除已存在的表。
3.1创建一个表
通过调用数据库的execSQL (String sql)方法可以创建一个table(表),关于execSQL(String sql)方法的详细可以参看以下的官方说明。
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 useinsert(String, String, ContentValues)
,update(String, ContentValues, String, String[])
, et al, when possible.
When using enableWriteAheadLogging()
, journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using enableWriteAheadLogging()
Parameters
sql | the SQL statement to be executed. Multiple statements separated by semicolons are not supported. |
---|
Throws
SQLException | if the SQL string is invalid |
---|
事实上,execSQL (String sql)方法的参数“sql“是SQL语句,为字符串类型。如
- SQLiteDatabase db;
- String sql = "CREATE TABLE pic (_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";
- db.execSQL(sql);
关于SQL语句可参看相关SQL的编程资料。
另外通过execSQL()方法,还可以实现向表中“插入”数据,“删除”数据。
同样是通过不同的SQL语句实现的。
- db.execSQL(sql);//sql为标准的SQL语句
另外:读取表中数据也可以用rawQuery();方法来读取。
public Cursor rawQuery (String sql,String[] selectionArgs)
Runs the provided SQL and returns a Cursor
over the result set.
Parameters
sql | the SQL query. The SQL string must not be ; terminated |
---|---|
selectionArgs | You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings. |
虽然db.execSQL(sql);方法也可以实现insert和delete操作,另外db.rawQuery(sql, selectionArgs);也可以查询表中的某一条数据,
但是由于涉及到标准SQL语句,所以一般来说,除了新建table是用execSQL(sql)方法和3.6点的删除一个table,其他的如insert,delete,query操作还是建议使用以下方法。
3.2、向表中插入一条数据
往数据库的table插入数据,可以直接调用db.insert()方法插入,但是insert()方法中的第三个参数是一个ContentValues的,其实也就是一个map,包含了一些键值对(key-value)。通过contentValues的put方法,可以把键值对放进contentValues里面,然后再通过db.insert()方法插到数据库的table中。
public long insert(String table,String nullColumnHack, ContentValues values)
Convenience 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 providedvalues is empty, no column names are known and an empty row can't be inserted. If not set to null, thenullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where yourvalues is 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 |
Returns
- the row ID of the newly inserted row, or -1 if an error occurred
insert的第一个参数是table的名字,
第二个参数一般为null,
第三个参数是contentValues,要插入的值value
成功insert,就返回新插入row的id,不成功返回-1。
- ContentValues cv =new contentValues();
- cv.put(num,1);
- cv.put(data," 测试我的数据库");
- db.insert(table,null,cv);
3.3、删除table中的一条数据
直接调用数据库的db.delete()方法。
public intdelete(String table,String whereClause,String[] whereArgs)
Convenience method for deleting rows in the database.
Parameters
table | the table to delete from |
---|---|
whereClause | the optional WHERE clause to apply when deleting. Passing null will delete all rows. |
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.
第二个参数————删除的条件,为字符串。如果为null,则所有行都将删除。
第三个参数————字符串数组,和whereClause配合使用。
用法一、如果whereClause的条件已经直接给出,如“name= “ + num,num是传入的参数。则whereArgs可设为null。当whereClause设置为null时,则删除所有行。
用法二、当在whereClause中包含”?”时,则whereArgs这个数组中的值将依次替换whereClause中出现的”?”
3.4、修改表中数据
调用db.update()方法
public int update(String table,ContentValues values,String whereClause,String[] whereArgs)
Convenience 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. |
Returns
- the number of rows affected
3.5、查询表中的数据
调用db.query()方法。
public 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.
Parameters
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. |
table————要查询数据的表名
columns————要返回列的列名数组
selection————可选的where子句 ,如果为null,将会返回所有的行
selectionArgs————当在selection中包含”?”时,如果selectionArgs的值不为null,则这个数组中的值将依次替换selection中出现的”?”
groupBy————可选的group by子句,如果其值为null,将不会对行进行分组
having————可选的having子句,如果其值为null,将会包含所有的分组
orderBy————可选的order by子句,如果其值为null,将会使用默认的排序规则
limit————可选的limit子句,如果其值为null,将不会包含limit子句
- Cursor cr=db.query("pic", null, null, null, null,null, null);//查询数据库的所有数据
返回值类型为Cursor(游标),Cursor的操作示意图
然后通过调用Cursor的相关方法来操作查询到的数据,关于Cursor的使用方法可以参看官方的说明文档,下面列出一些常用的方法:
3.6、删除一个table
通过db.execSQL(sql)方法实现,参数sql是SQL标准语句
- db.execSQl("DROP TABLE mytable");
关于SQLite的具体实现例子,可以点击以下的链接,参看另一篇博文