SQLite使用介绍2
插入数据
方法public long insert(String table, String nullColumnHack, ContentValues values);
- 参数String table:表名
- 参数String nullColumnHack:当values为null或是空的时候,表中值设为null的字段。
- 参数ContentValues values:要插入的值。
例:
private void insert(SQLiteDatabase db){
//实例化常量值
ContentValues cValue = new ContentValues();
cValue.put("product_id","001");
cValue.put("product_name","T恤衫");
cValue.put("product_type","衣服");
cValue.put("sale_price",1000);
cValue.put("purcgase_price",500);
cValue.put("regist_date","2009-09-20");
//调用insert()方法插入数据
db.insert("Product",null,cValue);
}
源码分析:
public long insert(String table, String nullColumnHack, ContentValues values) {
try {
return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
} catch (SQLException e) {
Log.e(TAG, "Error inserting " + values, e);
return -1;
}
}
public long insertWithOnConflict(String table, String nullColumnHack,
ContentValues initialValues, int conflictAlgorithm) {
acquireReference();
try {
StringBuilder sql = new StringBuilder();
sql.append("INSERT");
sql.append(CONFLICT_VALUES[conflictAlgorithm]);
sql.append(" INTO ");
sql.append(table);
sql.append('(');
Object[] bindArgs = null;
int size = (initialValues != null && !initialValues.isEmpty())
? initialValues.size() : 0;
if (size > 0) {
bindArgs = new Object[size];
int i = 0;
for (String colName : initialValues.keySet()) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
bindArgs[i++] = initialValues.get(colName);
}
sql.append(')');
sql.append(" VALUES (");
for (i = 0; i < size; i++) {
sql.append((i > 0) ? ",?" : "?");
}
} else { // 当initialValues为null或为空时
sql.append(nullColumnHack + ") VALUES (NULL");
}
sql.append(')');
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
try {
return statement.executeInsert();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
从上面的源码中分析知道,最后执行的还是SQL语句。所以是根据参数拼接成SQL语句。
注:从上面的源码知道,在使用insert()方法时,需要注意一点。就是参数String nullColumnHack和ContentValues values不能同时为null,且nullColumnHack一定要是表中的not null 约束的字段名。在同时为null时,拼接出来的SQL语句不是正常的SQL语句。
删除数据
方法public int delete(String table, String whereClause, String[] whereArgs);
- 参数String table:表名
- 参数String whereClause:删除的条件的属性名
- 参数String[] whereArgs:删除的条件的属性的值数组,这个数组中的值会安顺序代替whereClause中的”?”符号。
例:
private void delete(SQLiteDatabase db) {
//删除条件
String whereClause = "product_id=?";
String[] whereArgs = {"002"};
//执行删除
db.delete("Product",whereClause,whereArgs);
}
源码分析:
public int delete(String table, String whereClause, String[] whereArgs) {
acquireReference();
try {
SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
(!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
try {
return statement.executeUpdateDelete();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
从源码知道,删除语句最终也是拼接成SQL语句。当whereClause不为null 或”“ 时,SQL语句就会加上where whereClause 子句。最后String[] whereArgs数组中的值会代替whereClause中的”?“符号拼接成最终的SQL语句。
更新数据
方法public int update(String table, ContentValues values, String whereClause, String[] whereArgs);
- 参数String table:表名
- 参数ContentValues values:更新的值放在这个values里面
- 参数String whereClause:删除的条件的属性名
- 参数String[] whereArgs:删除的条件的属性的值数组,这个数组中的值会安顺序代替whereClause中的”?”符号。
例:
private void update(SQLiteDatabase db) {
//实例化内容值 ContentValues values = new ContentValues();
//在values中添加内容
values.put("product_type","工具");
//修改条件
String whereClause = "product_id=?";
//修改添加参数
String[] whereArgs={String.valuesOf("007")};
//修改
db.update("Product",values,whereClause,whereArgs);
}
源码:
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
}
public int updateWithOnConflict(String table, ContentValues values,
String whereClause, String[] whereArgs, int conflictAlgorithm) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException("Empty values");
}
acquireReference();
try {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(CONFLICT_VALUES[conflictAlgorithm]);
sql.append(table);
sql.append(" SET ");
// move all bind args to one array
int setValuesSize = values.size();
int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
Object[] bindArgs = new Object[bindArgsSize];
int i = 0;
for (String colName : values.keySet()) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
bindArgs[i++] = values.get(colName);
sql.append("=?");
}
if (whereArgs != null) {
for (i = setValuesSize; i < bindArgsSize; i++) {
bindArgs[i] = whereArgs[i - setValuesSize];
}
}
if (!TextUtils.isEmpty(whereClause)) {
sql.append(" WHERE ");
sql.append(whereClause);
}
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
try {
return statement.executeUpdateDelete();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
从源码中看出values不能为null或空,否则会抛异常。
查询数据
方法public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy) ;
- 参数String table:表名
- 参数String[] columns:要选取的字段
- 参数String selection:选取条件的字段名
- 参数String[] selectionArgs:选择条件的值,这个数据里面的值会逐一替代selection中的”?”。
- 参数groupBy:把表分组的字段名
- 参数String having:对表分组后的过滤条件
- 参数String orderBy:排序规则asc ,desc 。
例:
Cursor cursor = db.query(tableName , new String[]{"product_id" , "product_type" , "product_name" , "sale_price" , "purcgase_price" , "regist_date" } , "sale_price >=?" , new String[]{"100"} ,"product_type" , null , "product_id asc");
Cursor类介绍
- getCount()获得总的数据项数
- isFirst()判断是否第一条记录
- isLast()判断是否最后一条记录
- moveToFirst()移动到第一条记录
- moveToLast()移动到最后一条记录
- move(int offset)移动到指定记录
- moveToNext()移动到下一条记录
- moveToPrevious()移动到上一条记录
- getColumnIndexOrThrow(String columnName)根据列名称获得列索引
- getInt(int columnIndex)获得指定列索引的int类型值
- getString(int columnIndex)获得指定列缩影的String类型值