Original Digest from Http://www.tuicool.com/articles/jmmMnu
In a general database upgrade, you need to detect if a field (column) already exists in the table, because repeating the column name will result in an error. There are a number of ways to do this, and here are 2 common ways:
1, judging by the return value of Cursor.getcolumnindex (String columnName), if 1 indicates that there is no such field in the table
/*** Method 1: Check if a table column exists *@param db*@param tableName Table name *@param columnName Column Name *@return */private boolean checkColumnExist1 (sqlitedatabase db, String TableName, String columnName) {boolean result = false; cursor cursor = null; try{//query line cursor = db.rawquery ( "SELECT * from" + TableName + "LIMIT 0", null); result = cursor! = null && cursor.getcolumnindex (columnName)! =-1;} catch (Exception e) {log.e (Tag, "CheckColumnExists1 ..." + e.getmessage ()) ; }finally{if (null! = Cursor &&!) Cursor.isclosed ()) {cursor.close ();}} return result;}
2, by querying the SQLite system table Sqlite_master to find out whether the field exists in the corresponding table, a slight change of the statement can also look for the existence of tables
/*** Method 2: Check if a column exists in the table *@param db*@param tableName Table name *@param columnName Column Name *@return */Privateboolean checkColumnExists2 (Sqlitedatabase db, String tableName, String columnName) { Boolean result = false; cursor cursor = null; try{cursor = db.rawquery ( "select * from sqlite_master where name =? And SQL like? ", new String[]{tablename, "% "+ columnName + "% "}); result = NULL! = Cursor && C Ursor.movetofirst (); }catch (Exception e) {log.e (TAG,"checkColumnExists2 ..." + e.getmessage ());} finally{ if (null! = Cursor &&!cursor.isclosed ()) {cursor.close ();}} return result;}
I used the method 2, and then changed the table structure with alter, the same can be found out
ALTER TABLE Yuhuolixian add AAA integer NULL
SELECT * from sqlite_master where name = ' Yuhuolixian ' and SQL like '%aaa% '
Does SQLite query tables and fields exist