简体   繁体   English

在SQLiteDatabase中找不到记录

[英]Can't find a record in a SQLiteDatabase

In my application, I create a table for my database like this : 在我的应用程序中,我为数据库创建一个表,如下所示:

    String action;

    action= "CREATE TABLE ";
    action+=TABLE_LIEUX;
    action+="(Name TEXT NOT NULL PRIMARY KEY);";
    base.execSQL(action);

I then add a record to this table with : 然后,我使用以下命令向该表添加一条记录:

    ContentValues valeur;
    long InsertLine=-10;

    valeur=new ContentValues(1);
    valeur.put("Name","'"+name+"'");
    InsertLine=getWritableDatabase().insert(TABLE_LIEUX,null,valeur);

The value I get for InsertLine is 1, as expected. 我得到的InsertLine的值是1,如预期的那样。 But when I try to search for the row added with : 但是当我尝试搜索添加了以下内容的行时:

            result=(SQLiteCursor)getWritableDatabase().query(TABLE_LIEUX,null,"Name='"+name+"'",null,null,null,null);

the SQLiteCursor result I get has a length of -1. 我得到的SQLiteCursor结果的长度为-1。 And when I try to add the row again, I get an SQLiteException which indicates the row should be unique (so, despite the result of the search, the row is already in the database). 当我尝试再次添加行时,我得到一个SQLiteException ,该行指示该行应该是唯一的(因此,尽管搜索结果如此,但该行已在数据库中)。

Any idea? 任何想法?

You must force the Cursor to read the returned data (by calling moveToFirst or something like that) before you can get the cursor's record count. 在获取光标的记录计数之前,必须强制Cursor读取返回的数据(通过调用moveToFirst或类似方法)。

Furthermore, you must not quote values when using the ContentValues put function; 此外,在使用ContentValues put函数时,您不能引用任何值。 the value in the database now contains superfluous quotes. 数据库中的值现在包含多余的引号。

Why did you cast your query result to (SQLiteCursor)? 为什么将查询结果转换为(SQLiteCursor)? Query statements always return a Cursor object so bother with the cast. 查询语句总是返回一个Cursor对象,这样就麻烦转换了。

 Cursor result = getWritableDatabase().
 query(TABLE_LIEUX, null, "Name='"+name+
"'", null, null, null, null);

String mString;

if(result != null && c.moveToFirst()) {
     mString = result.getString(result.
 getColumnIndex("Name"));
}

hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM