【问题标题】:Get insert error code on sqlite在 sqlite 上获取插入错误代码
【发布时间】:2012-09-04 16:49:22
【问题描述】:
如何在 sqlite 数据库(在 android 中)上运行 sql 语句并获取查询结果?我需要确定查询是否被执行。
我想出了:
db.execSQL(sql);
但这是一个无效函数。
我从数据库中获取 query_string,所以我不知道是插入或更新或删除语句。我确信它不会是一个选择语句。
【问题讨论】:
标签:
android
sqlite
insert
error-code
【解决方案1】:
试试这样的:
public String insertQuery(String sql) {
try{
db.execSQL(sql);
}
catch (SQLException ex){
return ex.toString();
}
return null;
}
【解决方案2】:
如果你使用SQLiteDatabase,你可以做两件事:
1.) *无结果查询(UPDATE、DELETE、DROP、ALTER 等...)*
这些查询不返回任何值,它们会修改数据库。执行此操作的函数称为execSQL(String)。你可以简单地给它一个字符串格式的 SQL 查询,它就会执行它。
2.) *查询结果 (SELECT)*
这些查询将返回一个Cursor 对象。使用游标,您可以迭代结果集,就像使用任何其他迭代器一样。光标将始终“包含”实际结果集中的一行,您可以调用移动函数来向前/向后移动。执行此操作的函数称为rawQuery(String, String [])。你也可以使用query()函数,使用它,你必须输入更少的SQL。
一个例子:
Cursor cursor = database.rawQuery("SELECT * FROM yourtable", null);
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
/*this means you want to get from the current row a String
(CHAR, VARCHAR or TEXT) value from the 0th (first) column*/
String str = cursor.getString(0);
/*This means, that you want to get from the current row an
integer value from the 1st (second) column*/
int i = cursor.getInt(1);
...
}