sqlite - 从 SQLite 数据库中检索 Int 值
问题描述
我正在尝试从我的 SQLite 数据库中检索一个整数,而我当前的查询使我的程序崩溃。这是我到目前为止所拥有的:
*/
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
db.execSQL(query);
int win = Integer.parseInt(query);
return win;
}
我不确定为什么这不起作用。提前致谢。
解决方案
您正在尝试将值 SELECT ......... 转换为按int win = Integer.parseInt(query);
.
对于 SELECT 语句,您需要通过query或rawQuery SQLiteDatabase 方法检索游标(结果集),然后从方法中提取值,然后从相应的行访问相应的列.
我相信你会使用类似的东西: -
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1; //<<<<<<<<<< ADDED default value to return if no row found
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
Cursor csr = db.rawQuery(query,null); //<<<<<<<<<< CHANGED to get the Cursor returned
// ADDED the following IF construct
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
//int win = Integer.parseInt(query); //<<<<<<<<<< DELETED (commented out)
csr.close(); //<<<<<<<<<< ADDED should always close a Cursor when done with it
return rv; //<<<<<<<<<< return the value (-1 if no row found)
}
- 这假设您只需要 WHERE 子句标识的单行中的值。
如果可能,建议 a) 不使用直接值构建查询(使其容易受到 SQL 注入的攻击),并且 b) 使用便捷查询方法。
同时应用a和b,您的代码可能是:-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1;
String whereclause = COL2 + "=?"; //<<<<<<<<<< where clause without where and ? for value that will be passed
String[] whereargs = new String[]{String.valueOf(id)}; //<<<<<<<<<< arguments used by the whereclause ? replaced on a 1 for 1 basis
String[] columns = new String[]{COL3}; //<<<<<<<<<< the columns to extract as a String array
Cursor csr = db.query(TABLE_NAME,columns,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
csr.close();
return rv;
}
推荐阅读
- python - 为什么我的粘性波动方程在 python 模拟中爆炸?
- ios - Swift:在 UITableView 中使用 Cosmos
- xamarin - 如果我想允许其他开发人员在他的 iOS 设备上本地试用我的应用程序,iOS Keystore 包含什么?
- sql - 从 Oracle Enterprise Manager (OEM) 获取所有数据库和服务器名称的 SQL 查询
- ios - iOS - 在横向模式下获取状态栏高度和宽度 0
- javascript - SetInterval 未获取最新的道具值
- 3d - 使用深度图重新计算 2D 图像中点的 3D 坐标
- sulu - Sulu 2.0:如何从搜索命中访问 seo 描述?
- ruby-on-rails - Rails 出生日期确认验证
- sql - 尽管创建了 EXTENSION tablefunc,但 Postgres 中“START”处或附近的语法错误