如何使用Android在Sqlite数据库中找到用户? [英] How to find out user is present in Sqlite Database using android?

查看:172
本文介绍了如何使用Android在Sqlite数据库中找到用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用登录/注册应用程序进行培训,因为我是一个初学者,除了一个小问题,其他所有东西都在工作,但我不知道如何解决,我尝试搜索但找不到任何东西 这是我数据库的一部分.

I am working on a login/register app just for training as I am a beginner everything is working except for a small problem but I don't know how to fix it , I tried searching but couldn't find anything here is the part of my database.kt

   fun userPresent (user: String,pass: String):Boolean {
       val db = writableDatabase
       val query = "select * from $TABLE_NAME where username = $user and password = $pass"
       val cursor = db.rawQuery(query,null)

       if (cursor.count <= 0) {
           cursor.close()
           return false }
       cursor.close()
       return true }

mainactivity.kt

mainactivity.kt

if (database.userPresent(user = username,pass = password)) {
                intent.putExtra("text", "Welcome , $username $password")
                startActivity(intent)
                Toast.makeText(this,"Logged In Successfully",Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this,"Wrong Username/Password",Toast.LENGTH_SHORT).show()
            }

我的logCat错误

android.database.sqlite.SQLiteException: no such column: ss (code 1 SQLITE_ERROR): , while compiling: select * from user_table where username = ss and password = ss
at com.example.myapplication.DatabaseHelper.userPresent(DatabaseHelper.kt:52)
at com.example.myapplication.MainActivity$onCreate$1.onClick(MainActivity.kt:49)

我也不确定为什么您必须关闭光标. 预先谢谢你

also I am not sure on why you have to close the cursor. thank you in advance

推荐答案

您的代码存在的问题是,您将参数传递为Integer(您没有),但是这些参数是无法识别为TEXT文字,因为它们没有用单引号引起来,因此SQLite认为它们是列名.

The problem with your code is not that you pass the arguments as Integer (you don't), but that the arguments are not recognized as TEXT literals because they are not enclosed in single quotes, so SQLite thinks they are column names.

将参数传递给rawQuery()的推荐方法是:

The recommended way of passing the parameters to rawQuery() is this:

fun userPresent (user: String, pass: String): Boolean {
    val db = writableDatabase 
    val query = "select * from $TABLE_NAME where username = ? and password = ?"
    val cursor = db.rawQuery(query, arrayOf(user, pass))
    val result = cursor.count > 0
    cursor.close()
    db.close()
    return result
}

占位符?将从作为rawQuery()的第二个参数传递的数组的相应项目中获取其值,并且您无需将单引号连接在一起,从而避免了

The placeholders ? will take their values from the corresponding items of the array passed as the 2nd argument of rawQuery() and you don't need to concatenate the single quotes so you avoid the risk of sql injection.
After that and before the return statement you must close both the Cursor and the db object.

这篇关于如何使用Android在Sqlite数据库中找到用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆