c#优化选择字符串创建循环

标签 c# sql string optimization concatenation

我希望优化这段代码。它将处理 15000 - 20000 行。现在我有 9000 行,大约需要 30 秒。我知道字符串连接很慢,但我不知道如何用其他方式连接。

                    //
                    // Check if composite primary keys existe in database
                    //

                    string strSelect = "SELECT * FROM " + _strTableName + " WHERE ";
                    for (int i = 0; i < strCompositeKeyField.Length; i++)
                    {
                        bool boolKeyProcess = false;
                        strSelect += _strHeaderLineSplitedArray[(int)arrayListCompositeKeyIndex[i]] + " = ";
                        DataColumn thisColomn = _dsProcessDataFromFileAndPutInDataSetDataSet.Tables["Repartition"].Columns[_strHeaderLineSplitedArray[(int)arrayListCompositeKeyIndex[i]]];
                        //_strProcessDataFromFileAndPutInDataSetLog += "Debug: Composite key : " + _strHeaderLineSplitedArray[(int)arrayListCompositeKeyIndex[i]] + " dataType : " + thisColomn.DataType.ToString() + " arrayListCompositeKeyIndex[i] = " + arrayListCompositeKeyIndex[i] + " \n";
                        // check if field is datetime to make convertion
                        if (thisColomn.DataType.ToString() == "System.DateTime")
                        {
                            DateTime thisDateTime = DateTime.ParseExact(strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]], _strDateConvertion, null);
                            strSelect += "'" + thisDateTime.ToString() + "'";
                            boolKeyProcess = true;
                        }
                        // check if field a string to add ''
                        else if (thisColomn.DataType.ToString() == "System.String")
                        {
                            strSelect += "'" + strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]] + "'";
                            boolKeyProcess = true;
                        }
                        // check if field need hour to second converstion
                        else
                        {
                            for (int j = 0; j < strHourToSecondConverstionField.Length; j++)
                            {
                                if (strCompositeKeyField[i] == strHourToSecondConverstionField[j])
                                {
                                    DateTime thisDateTime = DateTime.ParseExact(strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]], _strHourConvertion, System.Globalization.CultureInfo.CurrentCulture);

                                    strSelect += thisDateTime.TimeOfDay.TotalSeconds.ToString();
                                    boolKeyProcess = true;
                                }
                            }
                        }
                        // if not allready process process as normal
                        if (!boolKeyProcess)
                        {
                            strSelect += strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]];
                        }
                        // Add " AND " if not last field
                        if (i != strCompositeKeyField.Length - 1)
                        {
                            strSelect += " AND ";
                        }

                    }


                    //_strProcessDataFromFileAndPutInDataSetLog += "Debug: SELECT = " + strSelect + "\n";

                    SqlDataAdapter AdapterCheckCompositePrimaryKeys = new SqlDataAdapter(strSelect, _scProcessDataFrinFileAndPutInDataSetSqlConnection);
                    DataSet DataSetCheckCompositePrimaryKeys = new DataSet();

                    AdapterCheckCompositePrimaryKeys.Fill(DataSetCheckCompositePrimaryKeys, "PrimaryKey");

最佳答案

你绝对应该看看StringBuilder - 它对像这样的场景有奇效。在这种情况下,我会混合使用 AppendFormatAppend .我倾向于喜欢AppendFormat使字符串更容易理解。

//
// Check if composite primary keys existe in database
//

StringBuilder strSelect = "SELECT * FROM " + _strTableName + " WHERE ";

for (int i = 0; i < strCompositeKeyField.Length; i++)
{
    bool boolKeyProcess = false;

    strSelect.AppendFormat("{0} =", 
        _strHeaderLineSplitedArray[(int)arrayListCompositeKeyIndex[i]]);

    DataColumn thisColomn = 
        _dsProcessDataFromFileAndPutInDataSetDataSet
        .Tables["Repartition"]
        .Columns[_strHeaderLineSplitedArray[(int)arrayListCompositeKeyIndex[i]]];

    //_strProcessDataFromFileAndPutInDataSetLog += "Debug: Composite key : " + _strHeaderLineSplitedArray[(int)arrayListCompositeKeyIndex[i]] + " dataType : " + thisColomn.DataType.ToString() + " arrayListCompositeKeyIndex[i] = " + arrayListCompositeKeyIndex[i] + " \n";
    // check if field is datetime to make convertion
    if (thisColomn.DataType.ToString() == "System.DateTime")
    {
        DateTime thisDateTime = 
            DateTime.ParseExact(strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]], 
           _strDateConvertion, null);

        strSelect.AppendFormat("'{0}'", thisDateTime.ToString());
        boolKeyProcess = true;
    }
    // check if field a string to add ''
    else if (thisColomn.DataType.ToString() == "System.String")
    {
        strSelect.AppendFormat("'{0}'", 
            strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]]);

        boolKeyProcess = true;
    }
    // check if field need hour to second converstion
    else
    {
        for (int j = 0; j < strHourToSecondConverstionField.Length; j++)
        {
            if (strCompositeKeyField[i] == strHourToSecondConverstionField[j])
            {
                DateTime thisDateTime = DateTime.ParseExact(
                    strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]],
                    _strHourConvertion, 
                    System.Globalization.CultureInfo.CurrentCulture);

                strSelect.Append(thisDateTime.TimeOfDay.TotalSeconds.ToString());
                boolKeyProcess = true;
            }
        }
    }
    // if not allready process process as normal
    if (!boolKeyProcess)
    {
        strSelect.Append(strReadDataLineSplited[(int)arrayListCompositeKeyIndex[i]]);
    }
    // Add " AND " if not last field
    if (i != strCompositeKeyField.Length - 1)
    {
        strSelect.Append(" AND ");
    }

}


//_strProcessDataFromFileAndPutInDataSetLog += "Debug: SELECT = " + strSelect + "\n";

SqlDataAdapter AdapterCheckCompositePrimaryKeys = new SqlDataAdapter(strSelect.ToString(), _scProcessDataFrinFileAndPutInDataSetSqlConnection);
DataSet DataSetCheckCompositePrimaryKeys = new DataSet();

AdapterCheckCompositePrimaryKeys.Fill(DataSetCheckCompositePrimaryKeys, "PrimaryKey");

关于c#优化选择字符串创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1840246/

相关文章:

c# - 如何使用 Json.NET StringEscapeHandling.EscapeNonAscii

c# - 使用 C# 发送邮件,使用客户端发送 Lotus Notes

c# - 插入、选择和更新日期时间

javascript - 为什么 'a' > 'A' 是真的?

python - 如何让用户对 raw_input( ) 的响应访问同名字符串?

c# - 用户通过 linq 等选择的日期范围到几周

c# - 如果我只在 HttpGet 上验证是否安全?

sql - 查询返回 MS SQL Server 列出的所有系统存储过程

具有任务依赖性的任务管理器应用程序的 MySQL 表结构

Java do-while 与多个字符串验证