使用C#以有效方式在MySQL数据库表中插入数千行

时间:2019-03-12 17:27:44

标签: c# mysql

我需要在MySQL数据库中插入未知数量的行。这些行在词典列表中。 列表中的每个字典代表一行。对于每一行,字典key包含列名,而value包含该行的列数据

我已经实现了这样的目标-

public long InsertMultiple(string TableName, List<Dictionary<string, string>> listMultipleRows)
{
    try
    {
        string columnNames = null;
        StringBuilder sCommand = new StringBuilder();
        List<string> Rows = new List<string>();
        int columnLength = listMultipleRows.First().Select(x => x.Key).ToArray().Length;

        //Fetching required column names.
        if (listMultipleRows.Count > 0)
            columnNames = string.Join(", ", listMultipleRows.First().Select(x => x.Key).ToArray());

        //Preparing command
        if (columnNames != null)
            sCommand = new StringBuilder("INSERT INTO " + TableName + " (" + columnNames + ") VALUES ");

        //Preparing column format like - '{0}','{1}'......
        string columnFormat = "(";
        for (int i = 0; i < columnLength; i++)
        {
            if (i != 0)
                columnFormat = columnFormat + ",";
            columnFormat = columnFormat + "'{" + i + "}'";
        }
        columnFormat = columnFormat + ")";                

        //Appending each row values. Actual rows which needs to be inserted.
        foreach (Dictionary<string, string> row in listMultipleRows)
        {
            Rows.Add(string.Format(columnFormat, row.Select(x => MySql.Data.MySqlClient.MySqlHelper.EscapeString(x.Value)).ToArray()));
        }

        sCommand.Append(string.Join(",", Rows));
        sCommand.Append(";");

        MySqlCommand Comm = new MySqlCommand();
        Comm.CommandText = sCommand.ToString();
        Comm.Connection = m_Conn;
        //One shot insertion operation
        return Convert.ToInt64(ExecuteScalar(Comm));  
    }
    catch (Exception Ex)
    {
        return 0;
    }
}
  

2800条记录的执行时间约为500毫秒。太棒了。   我担心的是SQL注入。通常,我们使用   参数化查询以避免SQL注入。但就我而言,   可以大量使用,因此不能创建太多参数。在那儿   这个问题的解决方案?还是更好的方法?

0 个答案:

没有答案
相关问题