Android SQLite数据库检查查询是否存在?

时间:2019-01-06 17:51:19

标签: android sqlite android-studio

嗨,我还是android和SQLite的新手。我得到的活动可以向附加的db文件中添加查询。 问题是,我无法使用我的方法添加数据。有没有简单的方法可以检查查询是否存在?

这是我的数据库访问权限

their.bat < nul

这是当我尝试调用方法

public class DBAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DBAccess instance;
Cursor c = null;

private DBAccess(Context context)
{
    this.openHelper = new DatabaseOpenHelper(context);
}

public static DBAccess getInstance(Context context)
{
    if(instance==null)
    {
        instance=new DBAccess(context);
    }
    return instance;
}

public void open()
{
    this.db = openHelper.getWritableDatabase();
}

public void close()
{
    if(db!=null)
    {
        this.db.close();
    }
}

public void tambah(String a,String b)
{
    String query= ("insert into TabelAbjad (kata,arti) values('"+a+"','"+b+"')");
    db.execSQL(query);
}

public boolean checkdata(String c, String d)
{
    String s;
    String query= ("select kata from TabelAbjad where kata = '"+c+"' AND kata = '"+d+"'");
    db.execSQL(query);
    return true;
}

P.S:我叫按钮中的方法

2 个答案:

答案 0 :(得分:0)

查询字符串中缺少分号(;)。 尝试使用String query= ("select kata from TabelAbjad where kata = '"+c+"' AND kata = '"+d+"';");输入所有查询字符串

答案 1 :(得分:0)

您的问题是表中的任何行都不会存在,列 kata 的值为 c 以及(AND)的值为 d 是不可能的,因为一列只能有一个值,因此不会提取任何行。

也许您想查找具有 c OR d

的行

在这种情况下,您可以使用:-

String query= ("select kata from TabelAbjad where kata = '"+c+"' OR kata = '"+d+"'");
  • AND 已更改为 OR

此外,根据<->

execSQL 无法返回结果
  

执行不是SELECT或任何其他SQL的单个SQL语句   返回数据的语句。 execSQL

因此,您需要使用 rawQuery 方法或便捷的 query 方法,建议使用后者,除非存在局限性,否则不能使用使用。因此,您应该尝试使用类似(OR或AND假设)的东西:-

public boolean checkdata(String c, String d)
    boolean rv = false;
    String whereargs = "kata=? OR kata=?"; // the WHERE clause less the WHERE keyword ? for the arguments (used on a 1 for 1 basis)
    String[] whereargs = new String[]{c,d}; // The arguments that will be substituted into the SQL
    String[] columns = new String[]{"kata"};
    Cursor csr = db.query("TabelAbjad",columns,whereclause,whereargs,null,null,null);
    if (csr.getCount() > 0) {
        rv = true;
    }
    csr.close();
    return rv;
}
  • 尽管这看起来似乎更复杂,但是它在构建底层SQL时具有优势,它可以防止SQL注入,并且可以正确地包围/转义(将值括在单引号中)等值)
  • 您将数据(行)检索到游标中(在这种情况下,您只是想知道是否有任何行符合给定条件,因此使用getCount()(它返回提取的行数,如果没有则返回0) ))。
  

有没有一种简单的方法可以检查查询是否存在?

我相信您真正要说的是可以检查查询是否返回了任何结果。

如上所述,查询通过 Cursor 返回数据(如表格,但根据查询,例如上面的Cursor将由许多行组成(0或还有一个名为 kata 的列(即查询为SELECT **kata** FROM .....)),因此您需要使用合适的方法。

您可以检查/访问众多方面/属性。通常,您可以在光标周围移动(例如while (your_cursor.moveToNext) {.... do things ....}可以用于遍历光标中的所有行)。 Cursor

一旦适当地定位在行上,则可以使用 get????(column_offset) 检索来自数据库的数据(其中column_offset是一个整数,其中0代表第一列,但是通常,使用getColumnIndex(column_name_as_a_string方法)检索实际偏移量要明智得多。

因此,假设您希望将第一行中的数据(字符串)提取到游标csr中,则可以使用:-

if (csr.moveToFirst()) {
   String mykata = csr.getString(csr.getColumnIndex("kata"));
}
csr.close(); // You should always close a cursor when done with it.
相关问题