Check if a column exists in SQLite

前端 未结 15 501
我寻月下人不归
我寻月下人不归 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;
        }
    }
    

提交回复
热议问题