如何检查SQLite表

时间:2017-01-14 07:58:37

标签: android sqlite android-sqlite

这是我的database

public void DBCreate() {
    SQLITEDATABASE = getActivity().openOrCreateDatabase("FavoritesDB", Context.MODE_PRIVATE, null);
    SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS favorite(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, word VARCHAR, meaning VARCHAR);");
}

这就是我创建新行的方式:

String query = "INSERT INTO favorite (word,meaning) VALUES('"+wordd+"', '"+mean+"');";
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
if (c.moveToFirst())
{      
      Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
                    SQLITEDATABASE.execSQL(query);
}
else
{
      Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}

我的问题是如何在将值插入表之前检查数据?

3 个答案:

答案 0 :(得分:0)

在插入执行选择查询之前,检查cursor大小是否> 0比记录已存在。

我不确定您为什么在查询中传递null

 Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);

而不是

Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your id1"});

或 如果你想选择所有记录,那么

Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite");

答案 1 :(得分:0)

试试这段代码:

    Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your_id_name"});
    Log("Cursor Count : " + c.getCount());
               if(c.getCount()>0)
                {
                Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();

                }
                else
                {
                   Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
                   SQLITEDATABASE.execSQL(query);
                }

您的选择查询应如下所示:

String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue;

答案 2 :(得分:0)

选项:

1)如果您不想重复列中的任何值,请将CREATE方法中的列设置设置为" UNIQUE"甚至" PRIMARY KEY"如果内容应该是识别的主键。因此,您可以避免重复,而无需检查。

2)循环通过桌子(我也是学生,所以我希望这很好):

    Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite", null);

    if (c.getCount() > 0) {

        String searchString = "some word"; // word you are about to insert

        while (c.moveToNext()) {

            c.moveToFirst();
            int colIndex = c.getColumnIndex("word");
            String wordInCurrentRow = c.getString(colIndex);

            if (!(wordInCurrentRow.equals(searchString))) {
                // insert method
            } else {
                // do nothing
                Log.d("word already existing", "nothing to insert");
            }
        }
    }