void android.database.sqlite.SQLiteDatabase.execSQL(String sql, Object[] bindArgs) throws SQLException
Execute a single SQLstatement that is NOT a SELECT/INSERT/UPDATE/DELETE.
For INSERTstatements, use any of the following instead.
· insert(String, String, ContentValues)
· insertOrThrow(String, String, ContentValues)
· insertWithOnConflict(String, String, ContentValues,int)
For UPDATEstatements, use any of the following instead.
· update(String, ContentValues, String, String [])
· updateWithOnConflict(String, ContentValues, String,String [], int)
For DELETEstatements, use any of the following instead.
· delete(String, String, String [])
For example, thefollowing are good candidates for using this method:
· ALTER TABLE
· CREATE or DROP table/ trigger / view / index / virtual table
· REINDEX
· RELEASE
· SAVEPOINT
· PRAGMA that returnsno data
When using enableWriteAheadLogging(), journal_mode isautomatically 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 tobe executed. Multiple statements separated by semicolons are not supported.
bindArgs only byte[], String,Long and Double are supported in bindArgs.
Throws:
SQLException - if the SQL stringis invalid
打开数据库(没有的话创建)
进行数据的操作
关闭数据库
o insert(String, String, ContentValues)
long android.database.sqlite.SQLiteDatabase.insert(String table, String nullColumnHack, ContentValues values)
Convenience(方便)method for inserting a row into the database.
Parameters:
table the table to insertthe row into
nullColumnHack
optional; may be null.可选;允许设为空
SQL doesn't allowinserting a completely empty row without naming at least one column(列)name. If your provided values is empty, no columnnames 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 toexplicitly(明确地) insert a NULL into in the case whereyour values is empty.
values this map containsthe initial column values for the row. The keys should be the column names andthe values the column values ——一个map形式的数据集 map中 key 是表的列名,key对应的值是插入的这一行长,对应这个key的值
【这里面value和nullColumnHack有一定的关系:如果value为null的且nullColumnHack为null,系统会尝试插入一行空值,但这是不被允许的,,,nullColumnHack如果不为null(并且这个值对应的列是可空的)的话就可也避免value为空的情况报错—That all.】
【不管第三个参数是否包含数据,执行Insert()方法必然会添加一条记录,如果第三个参数为空,会添加一条除主键之外其他字段值为Null的记录。Insert()方法内部实际上通过构造insert SQL语句完成数据的添加,Insert()方法的第二个参数用于指定空值字段的名称,相信大家对该参数会感到疑惑,该参数的作用是什么?是这样的:如果第三个参数values 为Null或者元素个数为0,由于Insert()方法要求必须添加一条除了主键之外其它字段为Null值的记录,为了满足SQL语法的需要, insert语句必须给定一个字段名,如:insert into person(name) values(NULL),倘若不给定字段名, insert语句就成了这样: insert into person() values(),显然这不满足标准SQL的语法】
Returns:
the row ID of thenewly inserted row, or -1 if an error occurred
//=======================================================
private void insertData()
{
// insert(String table, StringnullColumnHack, ContentValues values)
// 由创建表的语句可以知道所有列都是允许为空的。
ContentValuescontentValues = new ContentValues();
contentValues.put("name", "电信");
contentValues.put("telephone", "10000");
sqlDB_1.insert("bussness_card", "id", contentValues);//报空指针错误
}
//============================================================
o insertOrThrow(String, String, ContentValues)
注释跟上一个函数相同
o insertWithOnConflict(String, String, ContentValues,int)
Generalmethod for inserting a row into the database.
Parameters:
tablethe table to insert the row into
nullColumnHackoptional; may be null
.SQL doesn't allow inserting a completely empty row without naming at least onecolumn name. If your provided initialValues
is empty, no column names are known and an empty row can't be inserted. If notset to null, the nullColumnHack
parameter provides the name of nullable column name to explicitly insert a NULLinto in the case where your initialValues
is empty.
initialValuesthis map contains the initial column values for the row. The keys should be thecolumn names and the values the column values
conflictAlgorithmfor insert conflict resolver
Returns:
therow ID of the newly inserted row OR the primary key of the existing row if theinput param 'conflictAlgorithm' = CONFLICT_IGNORE
OR -1 if any error
conflictAlgorithm的值 【除却这个参数的值基本与insert(……) 方法的注释相同】——但是没有明白这个参数的作用——望有心者留言
CONFLICT_NONE Use the following when no conflict action isspecified.
CONFLICT_ROLLBACK When a constraint violation occurs, animmediate ROLLBACK occurs, thus ending the current transaction, and the commandaborts with a return code of SQLITE_CONSTRAINT. If no transaction is active(other than the implied transaction that is created on every command) then thisalgorithm works the same as ABORT.
CONFLICT_ABORT When a constraint violation occurs,noROLLBACK is executed so changes from prior commands within the same transactionare preserved. This is the default behavior.
CONFLICT_FAIL When a constraint violation occurs, thecommand aborts with a return code SQLITE_CONSTRAINT. But any changes to thedatabase that the command made prior to encountering the constraint violationare preserved and are not backed out.
CONFLICT_IGNORE When a constraint violation occurs, the onerow that contains the constraint violation is not inserted or changed. But thecommand continues executing normally. Other rows before and after the row thatcontained the constraint violation continue to be inserted or updated normally.No error is returned.
CONFLICT_REPLACE When a UNIQUEconstraint violation occurs, the pre-existing rows that are causing theconstraint violation are removed prior to inserting or updating the currentrow. Thus the insert or update always occurs. The command continues executingnormally. No error is returned. If a NOT NULL constraint violation occurs, theNULL value is replaced by the default value for that column. If the column hasno default value, then the ABORT algorithm is used. If a CHECK constraintviolation occurs then the IGNORE algorithm is used. When this conflictresolution strategy deletes rows in order to satisfy a constraint, it does notinvoke delete triggers on those rows. This behavior might change in a futurerelease.
o execSQL(String sql, Object[] bindArgs)
很明显三个函数都是
public longinsertWithOnConflict(String table, String nullColumnHack, ContentValuesinitialValues, int conflictAlgorithm)
这一个函数
接下来分析一下它
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 insertOrThrow(String table, String nullColumnHack, ContentValues values) throws SQLException { return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE); }
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.size() > 0) ? 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 { sql.append(nullColumnHack + ") VALUES (NULL"); } sql.append(')');
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs); try { return statement.executeInsert(); } finally { statement.close(); } } finally { releaseReference(); } } |
以上4个方法
先是:
insert(String, String, ContentValues)
insertOrThrow(String, String, ContentValues)
调用到
insertWithOnConflict(String, String, ContentValues,int)
后
insertWithOnConflict(String, String, ContentValues,int)
execSQL(String sql, Object[] bindArgs)
殊途同归调用到
public abstract classSQLiteProgram
此类中的 构造函数
———关于插入的方法先探寻到这里
① delete(String, String, String [])
Convenience(方便)method for deleting rows in the database.
Parameters:
table the table to deletefrom
whereClause the optional WHEREclause(字句) to apply when deleting. Passingnull will delete all rows.
whereArgs You may include ?sin the where clause, which will be replaced by the values from whereArgs. Thevalues will be bound as Strings.
Returns:
the number of rowsaffected if a whereClause is passed in, 0 otherwise. To remove all rows and geta count pass "1" as the whereClause.
看不懂没关系值结贴代码
【SQL 中delete是用来删除行的】
1. private void delete(SQLiteDatabase db) {
2.
3. //删除条件
4. String whereClause = "_id=?";
5.
6. //删除条件参数
7. String[] whereArgs = {String.valueOf(2)};
8.
9. //执行删除
10. db.delete("stu_table",whereClause,whereArgs);
11. }
第二种方法的代码:
1. private void delete(SQLiteDatabase db) {
2.
3. //删除SQL语句
4. String sql = "delete from stu_table where _id = 6";
5.
6. //执行SQL语句
7. db.execSQL(sql);
8. }
private void deleteData()
{
sqlDB_1.delete("bussness_card", "id=?", new String[]{"5"});
sqlDB_1.delete("bussness_card", "id=? AND telephone=?", new String[]{"1","10000"});
//想要删除所有行却不删除表,,还会找到——SQLiteStatement——【突然有搞他一下的冲动】
sqlDB_1.delete("bussness_card", whereClause, whereArgs);
}
【让我们来分析下】
sqlDB_1.delete("bussness_card", "id=?", new String[]{"1"});
这句代码调用的方法:
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();
}
}
SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table + (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
DELETE FROM table