2011-01-18 35 views

Trả lời

36

cursor.getColumnIndex(String columnName) trả về -1 nếu cột không tồn tại. Vì vậy, tôi về cơ bản sẽ thực hiện một truy vấn đơn giản như "SELECT * FROM xxx LIMIT 0,1" và sử dụng con trỏ để xác định xem các cột, bạn đang tìm kiếm, tồn tại

HOẶC

bạn có thể thử để truy vấn cột "SELECT theCol TỪ xxx" và bắt một ngoại lệ

+0

Đó là những gì tôi nghĩ, nhưng tôi nhận được một SQLiteException nói "không có cột như: test ". Tôi đang kiểm tra xem cột có nằm trong bảng hay không và sau đó chèn nó vào. – Lunchbox

+0

bạn có nhận được ngoại lệ trong khi truy vấn hoặc trong getColumnIndex không? Nếu durig truy vấn: bạn có chắc bạn không chỉ định cột bạn kiểm tra trong truy vấn (không làm "SELECT col FROM ..." nhưng thực hiện "SELECT * FROM .." thay thế)? nếu không nó sẽ ném lỗi bạn đang đề cập đến và bạn phải bắt nó. – martinpelant

+0

Điều này xảy ra trong khi truy vấn. Tôi đang sử dụng SQLiteQueryBuilder để xây dựng truy vấn và cung cấp cho nó một bản đồ chiếu trải dài các cột trong bảng. – Lunchbox

4

tôi thực sự đã viết chức năng này mà dường như khá sạch:

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 ; 
} 

tôi gọi nó là như thế này:

if (field_exists("select * from sqlite_master "    
    + "where name = 'mytable' and sql like '%myfield%' ")) 
{ 
    do_something ; 
} 
29

chức năng của tôi dựa trên @martinpelants trả lời:

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(); 
    } 
} 

Đơn giản chỉ cần gọi:

boolean bla = existsColumnInTable(myDB,"MyTable","myColumn2check"); 
+6

Bạn nên đóng con trỏ trong khối 'cuối cùng'! – WonderCsabo

3

Đây là giải pháp của tôi để các vấn đề mà thêm vào của Flexo giải pháp một chút.

Bạn có thể đặt phương thức này trong bất kỳ lớp nào, có lẽ lớp mở rộng SQLiteOpenHelper của bạn.

public static boolean columnExistsInTable(SQLiteDatabase db, String table, String columnToCheck) { 
    Cursor cursor = null; 
    try { 
     //query a row. don't acquire db lock 
     cursor = db.rawQuery("SELECT * FROM " + table + " LIMIT 0", null); 

     // getColumnIndex() will return the index of the column 
     //in the table if it exists, otherwise it will return -1 
     if (cursor.getColumnIndex(columnToCheck) != -1) { 
      //great, the column exists 
      return true; 
     }else { 
      //sorry, the column does not exist 
      return false; 
     } 

    } catch (SQLiteException Exp) { 
     //Something went wrong with SQLite. 
     //If the table exists and your query was good, 
     //the problem is likely that the column doesn't exist in the table. 
     return false; 
    } finally { 
     //close the db if you no longer need it 
     if (db != null) db.close(); 
     //close the cursor 
     if (cursor != null) cursor.close(); 
    } 
} 
+1

Điều này có vẻ sạch hơn nhiều, nhưng tôi không chắc chắn rằng nó luôn luôn là một ý tưởng tốt để đóng cơ sở dữ liệu. –

+1

Vâng @ ban-geoengineering Tôi đã không chắc chắn về điều đó và đó là lý do tại sao tôi nói để đóng nó chỉ khi bạn không còn cần nó. – lwdthe1

2

Nếu bạn sử dụng ActiveAndroid

public static boolean createIfNeedColumn(Class<? extends Model> type, String column) { 
     boolean isFound = false; 
     TableInfo tableInfo = new TableInfo(type); 

     Collection<Field> columns = tableInfo.getFields(); 
     for (Field f : columns) { 
      if (column.equals(f.getName())) { 
       isFound = true; 
       break; 
      } 
     } 
     if (!isFound) { 
      ActiveAndroid.execSQL("ALTER TABLE " + tableInfo.getTableName() + " ADD COLUMN " + column + " TEXT;"); 
     } 
     return isFound; 
    } 
0

này là mã thử nghiệm của tôi:

String neadle = "id"; //searched field name 
String tableName = "TableName"; 
boolean found = false; 

SQLiteDatabase mDb = ActiveAndroid.getDatabase(); 
Cursor mCursor = mDb.rawQuery("SELECT * FROM sqlite_master WHERE name = '"+tableName+"' and sql like '%"+neadle+"%'" , null); 
mCursor.moveToFirst(); 
String fie = ","; 

if (mCursor.getCount() > 0) { 
    String[] fields = mCursor.getString(mCursor.getColumnIndex("sql")).split(","); 
    for (String field: fields) { 
     String[] fieldNameType = field.trim().split(" "); 
     if (fieldNameType.length > 0){ 
      fie += fieldNameType[0]+","; 
     } 
    } 
}else { 
    //table not exist! 
} 
if (mCursor != null) mCursor.close(); 
// return result: 
found = fie.contains(","+neadle+","); 
+0

cho ActiveAndroid bạn có thể lấy tên bảng từ lớp với mã này: – Tom

+0

Cache.getTableInfo (type) .getTableName() – Tom

Các vấn đề liên quan