我想知道使用ContentValues插入数据和在SQLlite(Android)中使用原始SQL插入数据的区别,使用内容值有优势吗?
发布于 2017-04-17 06:17:12
要执行插入、读取、删除和更新操作,有两种不同的方法:
参数化查询:这些查询使用内置函数来插入、读取、删除或更新数据。这些操作相关的函数都是在SQLiteDatabase类中提供的。
原始查询:这些是类似于其他数据库(如MySql、Server等)的简单sql查询,在这种情况下,用户必须将查询写成文本,并在rawQuery(String sql,String [] selectionArgs)或execSQL(String sql,Object [] bindArgs)方法中传递查询字符串来执行操作。
重要注释:文档不建议使用原始查询来执行插入、读取、更新、删除操作,总是使用SQLiteDatabase类的插入、查询、更新、删除函数。
以下是插入数据的原始查询示例:
public void insertItem(Item item) {
String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)";
SQLiteDatabase db = getWritableDatabase();
db.execSQL(query, new String[]{item.name, item.description});
db.close();
}在使用原始查询时,我们永远不会知道操作的结果,但是对于参数化的查询函数,会返回一个值来判断操作的成功或失败。
insert :要使用parameterized query执行插入操作,我们必须调用SQLiteDatabase类中可用的insert函数。insert()函数有三个参数,如public long insert(String tableName,String nullColumnHack,ContentValues values),其中tableName是要插入数据的表的名称。
下面是一个简单的例子:
//Item is a class representing any item with id, name and description.
public void addItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",item.name);
// name - column
contentValues.put("description",item.description);
// description is column in items table, item.description has value for description
db.insert("Items", null, contentValues);//Items is table name
db.close();
}有关更多信息,请参见此链接
https://stackoverflow.com/questions/43446062
复制相似问题