コード例 #1
0
ファイル: SqlFunc.cs プロジェクト: adamwoodhead/mysql-handler
        /// <summary>
        /// Alter Table with new Column
        /// </summary>
        /// <param name="table"></param>
        /// <param name="col"></param>
        /// <param name="sqlObject"></param>
        /// <returns></returns>
        internal static bool Table_Alter_Add_Column(string table, string col, SqlObject sqlObject)
        {
            SqlColumnAttribute sqlColumnAttrib = null;

            foreach (PropertyInfo property in Converter.GetPropertiesWithSqlColumnAttribute(sqlObject.AttachedObject.GetType()))
            {
                if (property != null)
                {
                    sqlColumnAttrib = (property.GetCustomAttributes(false).FirstOrDefault(x => x.GetType() == typeof(SqlColumnAttribute) && (x as SqlColumnAttribute).ColumnName == col) as SqlColumnAttribute);

                    if (sqlColumnAttrib != null)
                    {
                        break;
                    }
                }
            }

            Logger.Verbose($"Alter Table: {table}, Add Column {col}");

            using (MySqlConnection sqlConnection = new MySqlConnection(ConnectionString))
            {
                sqlConnection.Open();

                using (MySqlCommand Command = sqlConnection.CreateCommand())
                {
                    Command.CommandText = $"ALTER TABLE `{table}` ADD COLUMN `{col}` {sqlColumnAttrib.PropertyType}{((sqlColumnAttrib.AllowNull) ? "" : " NOT NULL")};";

                    Command.ExecuteNonQuery();

                    if (Column_Exists(table, col))
                    {
                        return(true);
                    }

                    return(false);
                }
            }
        }