BF2Statistics.Database.QueryBuilder.InsertQueryBuilder.BuildQuery C# (CSharp) Method

BuildQuery() protected method

Builds the query string or DbCommand
protected BuildQuery ( bool BuildCommand ) : object
BuildCommand bool
return object
        protected object BuildQuery(bool BuildCommand)
        {
            // Make sure we have a valid DB driver
            if (BuildCommand && Driver == null)
                throw new Exception("Cannot build a command when the Db Drvier hasn't been specified. Call SetDbDriver first.");

            // Make sure we have a table name
            if (String.IsNullOrWhiteSpace(Table))
                throw new Exception("Table to insert into was not set.");

            // Make sure we have at least 1 field to update
            if (Fields.Count == 0)
                throw new Exception("No fields to insert");

            // Create Command
            DbCommand Command = (BuildCommand) ? Driver.CreateCommand(null) : null;

            // Start Query
            StringBuilder Query = new StringBuilder("INSERT INTO " + Table + " (");
            StringBuilder Values = new StringBuilder();
            bool First = true;

            // Add fields and values
            foreach (KeyValuePair<string, object> Item in Fields)
            {
                // Append comma
                if (!First)
                {
                    Query.Append(", ");
                    Values.Append(", ");
                }
                else 
                    First = false;

                // If using a command, Convert values to Parameters
                if (BuildCommand && Item.Value != null && Item.Value != DBNull.Value && !(Item.Value is SqlLiteral))
                {
                    // Create param for value
                    DbParameter Param = Command.CreateParameter();
                    Param.ParameterName = "@P" + Command.Parameters.Count;
                    Param.Value = Item.Value;

                    // Add Params to command
                    Command.Parameters.Add(Param);

                    // Append query's
                    Query.Append(Item.Key);
                    Values.Append(Param.ParameterName);
                }
                else
                {
                    Query.Append(Item.Key);
                    Values.Append(WhereStatement.FormatSQLValue(Item.Value));
                }
            }

            // Finish the query string, and return the proper object
            Query.Append(") VALUES (" + Values.ToString() + ")");

            // Set the command text
            if (BuildCommand) Command.CommandText = Query.ToString();
            return (BuildCommand) ? Command as object : Query.ToString();
        }

Same methods

InsertQueryBuilder::BuildQuery ( ) : string