Lun*_*box 25 database sqlite android
在Android中是否有一种很好的方法来查看应用程序数据库中的表中是否存在列?(我知道有一些类似于这个的问题,但似乎没有任何Android特定的.)
mar*_*ant 45
cursor.getColumnIndex(String columnName)如果列不存在则返回-1.所以我基本上会执行一个简单的查询,如"SELECT*FROM xxx LIMIT 0,1",并使用光标确定您所寻找的列是否存在
要么
您可以尝试查询"SELECT theCol FROM xxx"列并捕获异常
fle*_*exo 34
我的功能基于@martinpelants回答:
private boolean existsColumnInTable(SQLiteDatabase inDatabase, String inTable, String columnToCheck) {
Cursor mCursor = null;
try {
// Query 1 row
mCursor = inDatabase.rawQuery("SELECT * FROM " + inTable + " LIMIT 0", null);
// getColumnIndex() gives us the index (0 to ...) of the column - otherwise we get a -1
if (mCursor.getColumnIndex(columnToCheck) != -1)
return true;
else
return false;
} catch (Exception Exp) {
// Something went wrong. Missing the database? The table?
Log.d("... - existsColumnInTable", "When checking whether a column exists in the table, an error occurred: " + Exp.getMessage());
return false;
} finally {
if (mCursor != null) mCursor.close();
}
}
Run Code Online (Sandbox Code Playgroud)
只需致电:
boolean bla = existsColumnInTable(myDB,"MyTable","myColumn2check");
Run Code Online (Sandbox Code Playgroud)
我实际上写了这个看起来很干净的函数:
private boolean field_exists( String p_query )
{
Cursor mCursor = mDb.rawQuery( p_query, null );
if ( ( mCursor != null ) && ( mCursor.moveToFirst()) )
{
mCursor.close();
return true ;
}
mCursor.close();
return false ;
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它:
if ( field_exists( "select * from sqlite_master "
+ "where name = 'mytable' and sql like '%myfield%' " ))
{
do_something ;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22347 次 |
| 最近记录: |