Check if a column exists in SQLite

前端 未结 15 493
我寻月下人不归
我寻月下人不归 2020-12-08 07:02

I need to check to see if a column exists and if it doesn\'t exist add it. From my research it looks like sqlite doesn\'t support IF statements and case statement should be

相关标签:
15条回答
  • 2020-12-08 07:05

    A weird way to check for existing column

    public static bool SqliteColumnExists(this SQLiteCommand cmd, string table, string column)
    {
        lock (cmd.Connection)
        {
            // make sure table exists
            cmd.CommandText = string.Format("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '{0}'", table);
            var reader = cmd.ExecuteReader();
    
            if (reader.Read())
            {
                //does column exists?
                bool hascol = reader.GetString(0).Contains(String.Format("\"{0}\"", column));
                reader.Close();
                return hascol;
            }
            reader.Close();
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-08 07:07

    Use with a try, catch and finally for any rawQuery() executions for better practices. And the following code will give you the result.

    public boolean isColumnExist(String tableName, String columnName)
    {
        boolean isExist = false;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
            if (cursor.moveToFirst()) {
                do {
                    String currentColumn = cursor.getString(cursor.getColumnIndex("name"));
                    if (currentColumn.equals(columnName)) {
                        isExist = true;
                    }
                } while (cursor.moveToNext());
    
            }
        }catch (Exception ex)
        {
            Log.e(TAG, "isColumnExist: "+ex.getMessage(),ex );
        }
        finally {
            if (cursor != null)
                cursor.close();
            db.close();
        }
        return isExist;
    }
    
    0 讨论(0)
  • 2020-12-08 07:11

    Some of these examples didn't worked for me. I'm trying to check whether my table already contains a column or not.

    I'm using this snippet:

    public boolean tableHasColumn(SQLiteDatabase db, String tableName, String columnName) {
        boolean isExist = false;
        Cursor cursor = db.rawQuery("PRAGMA table_info("+tableName+")",null);
        int cursorCount = cursor.getCount();
        for (int i = 1; i < cursorCount; i++ ) {
            cursor.moveToPosition(i);
            String storedSqlColumnName = cursor.getString(cursor.getColumnIndex("name"));
            if (columnName.equals(storedSqlColumnName)) {
                isExist = true;
            }
        }
        return isExist;
    }
    

    The examples above are querying the pragma table which is a metadata table and not the actual data, each column indicates the names, type and some other stuff about the table's columns. So the actual column names are within the rows.

    Hope that this helps someone else.

    0 讨论(0)
  • 2020-12-08 07:12
    SELECT EXISTS (SELECT * FROM sqlite_master WHERE tbl_name = 'TableName' AND sql LIKE '%ColumnName%');
    

    ..be aware of the LIKE condition which is imperfect, but it works for me as all my columns have very unique names..

    0 讨论(0)
  • 2020-12-08 07:14

    Althought this is an old question, I found at PRAGMA functions a simpler solution:

    SELECT COUNT(*) AS CNTREC FROM pragma_table_info('tablename') WHERE name='column_name'
    

    If the result is more than zero then the column exists. Simple and one line query

    The trick is to use

    pragma_table_info('tablename')
    

    instead of

    PRAGMA table_info(tablename)
    

    Edit: Please note that, as reported in PRAGMA functions:

    This feature is experimental and is subject to change. Further documentation will become available if and when the table-valued functions for PRAGMAs feature becomes officially supported.

    The table-valued functions for PRAGMA feature was added in SQLite version 3.16.0 (2017-01-02). Prior versions of SQLite cannot use this feature.

    0 讨论(0)
  • 2020-12-08 07:14
      public static bool columExsist(string table, string column)
        {
            string dbPath = Path.Combine(Util.ApplicationDirectory, "LocalStorage.db");
    
            connection = new SqliteConnection("Data Source=" + dbPath);
            connection.Open();
    
            DataTable ColsTable = connection.GetSchema("Columns");
    
            connection.Close();
    
            var data = ColsTable.Select(string.Format("COLUMN_NAME='{1}' AND TABLE_NAME='{0}1'", table, column));
    
            return data.Length == 1;
        }
    
    0 讨论(0)
提交回复
热议问题