检查数据库是否包含特定主键值的最有效方法是什么?
What's the most efficient way to check if DB contains a specific primary key value?
我想做这样的事情:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
// what should i do here to determine if the db contains the primaryKey?
}
检查数据库是否包含指定值的最有效方法是什么?
您应该检查 sqlite 方案。你可以试试
"SELECT name FROM sqlite_master WHERE type='table'"
第二种变体:
PRAGMA table_info(table-name);
如果您要获取 table 的列名称:
PRAGMA table_info(your_table_name);
示例:
PRAGMA table_info(Login);
如果你在登录时有主键,你将获得pk值1 table。
在 PRAGMA
上查看本教程
This pragma returns one row for each column in the named table.
Columns in the result set include the column name, data type, whether
or not the column can be NULL, and the default value for the column.
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
您可以尝试读取具有该 PK 值的行:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query("TableName", null, "IDColumn = " + primaryKey,
null, null, null, null);
return cursor.moveToFirst();
}
但是,最好使用 helper function 来避免使用光标:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "TableName", "IDColumn = " + primaryKey) > 0;
}
我想做这样的事情:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
// what should i do here to determine if the db contains the primaryKey?
}
检查数据库是否包含指定值的最有效方法是什么?
您应该检查 sqlite 方案。你可以试试
"SELECT name FROM sqlite_master WHERE type='table'"
第二种变体:
PRAGMA table_info(table-name);
如果您要获取 table 的列名称:
PRAGMA table_info(your_table_name);
示例:
PRAGMA table_info(Login);
如果你在登录时有主键,你将获得pk值1 table。
在 PRAGMA
上查看本教程This pragma returns one row for each column in the named table. Columns in the result set include the column name, data type, whether or not the column can be NULL, and the default value for the column. The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.
您可以尝试读取具有该 PK 值的行:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query("TableName", null, "IDColumn = " + primaryKey,
null, null, null, null);
return cursor.moveToFirst();
}
但是,最好使用 helper function 来避免使用光标:
public boolean containsKey(int primaryKey) {
SQLiteDatabase db = getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "TableName", "IDColumn = " + primaryKey) > 0;
}