在一个查询中使用 MySqlCommand 将多条记录插入 MySQL C# (MySQLConnector) &用于转义引号的命令参数

发布于 2024-11-08 05:51:17 字数 2390 浏览 0 评论 0原文

我正在尝试使用 C# 中的 MySqlCommand 对象(使用 MySQL 连接器库)在一个查询中将多条记录插入到表中。

我知道如何做到这一点的唯一方法是自己动态构建查询并设置command.CommandType = CommandType.Text;

此方法的问题是字段不会针对引号等进行转义。我想我可以自己编写一个函数来转义这些值,但是我在互联网上读过的每篇文章或问题似乎都对此不以为然,并说使用 command.Parameters 因为这样更有效和彻底。

我的问题是我不知道如何设置多行的参数。我怎样才能做到这一点?

编辑:这是一个24/7运行的商业服务,所以我需要找到最有效的方法来做到这一点。我没有使用存储过程 - 这是唯一的方法还是还有其他方法?

    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();
            }
        }
    }

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();
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南笙 2024-11-15 05:51:17

我不确定如何创建单个命令。我所做的是创建一个使用参数的方法,然后传入我想要一次运行一个的值。

我的方法:

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();
            }
        }

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();
            }
        }
如痴如狂 2024-11-15 05:51:17

我最终只使用了我已经编写的函数,因为它在一个命令中完成了所有操作,并使用:

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

它工作正常,所以我将看看事情进展如何。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文