3

I am trying to insert multiple records into a table in one query using the MySqlCommand object in C# (using the MySQL Connector library).

The only way I know how to do this is by dynamically constructing the query myself and setting command.CommandType = CommandType.Text;

The problem with this method is that the fields are not escaped for quotes and such. I could write a function to escape the values myself I guess, but every article or question I have read on the internet appears to frown upon this, and says use command.Parameters as this more efficient and thorough.

My problem is that I don't know how to set the parameters for multiple rows. How can I do that?

Edit: This is for a commercial service which runs 24/7, so I need to find the most efficient way to do this. I'm not using stored procedures - is this is the only way or is there another?

    public static string MySqlEscape(object value)
    {
        string val = value.ToString();
        if (val.Contains("'"))
            return val.Replace("'", "' + NCHAR(96) + '");
        else
            return val;
    }

    public void InsertProcessedData(long unprocessedID, long pagerID, long firmwareRelativeProtocolID, DataTable processedData)
    {
        using(processedData)
        {
            string paramColNames = string.Empty;
            for(int i =1;i<=processedData.Columns.Count;i+=1)
            {
                paramColNames+=string.Format("Param{0}",i);
                if(i!=processedData.Columns.Count)
                    paramColNames+=",";
            }

            string SQL = "INSERT INTO gprs_data_processed (@UnprocessedID,@PagerID,@FirmwareRelativeProtocolID,"+paramColNames+") VALUES ";

            for (int i = 0; i < processedData.Rows.Count;i+=1)
            {
                SQL += string.Format("({0},{1},{2},", unprocessedID, pagerID, firmwareRelativeProtocolID);
                for (int c = 0; c < processedData.Columns.Count; c += 1)
                {
                    SQL += string.Format("'{0}'", MySqlEscape(processedData.Rows[i][c]));
                    if (i != processedData.Columns.Count)
                        SQL += ",";
                }
                SQL+=")";
                if (i + 1 != processedData.Rows.Count)
                    SQL += ",";
                else
                    SQL += ";";
            }

            using (MySqlConnection connection = new MySqlConnection(_connection))
            {
                connection.Open();
                using (MySqlCommand command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = SQL;
                    command.ExecuteNonQuery();
                }
                connection.Close();
            }
        }
    }

2 Answers 2

1

I'm not sure on how to create a single command. What I do is create a method that uses parameters and then pass in the values that I want to run one at a time.

My method:

public void Insert(string strSQL, string[,] parameterValue)
        {

            //open connection
            if (this.OpenConnection() == true)
            {
                //create command and assign the query and connection from the constructor
                MySqlCommand cmd = new MySqlCommand(strSQL, connection);

                //add parameters
                for (int i = 0; i < (parameterValue.Length / 2); i++)
                {
                    cmd.Parameters.AddWithValue(parameterValue[i, 0], parameterValue[i, 1]);
                }

                //Execute command
                cmd.ExecuteNonQuery();

                //close connection
                this.CloseConnection();
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

1

I have ended up just using the function I have written already as it does it all in one command, and use:

public static string MySqlEscape(object value)
{
    string val = value.ToString();
    if (val.Contains("'"))
        return val.Replace("'", "''");
    else
        return val;
}

It works fine so I will see how things go.

1 Comment

I ended up in the same situation. The thing is, the MySQL DotNet Connector does have a Escaping method. Out of unknown reasons, I cannot use it though. Its in MySql.Data.MySqlClient.MySqlHelper

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.