C# 捕捉错误';在一个sqlcommand中执行多个插入时,执行多个命令行

C# 捕捉错误';在一个sqlcommand中执行多个插入时,执行多个命令行,c#,sql-server,sqlcommand,C#,Sql Server,Sqlcommand,我必须在我的应用程序的一个sqlcommand中自动执行多个sqlinsert命令,并且我必须在执行c#的sqlcommand中保留无法执行(由于错误)的insert命令。 顺便说一下,我不希望错误阻止继续执行查询 有什么建议吗 谢谢您在SQL语句中使用try-catch 请参阅并使用SQL语句中的try-catch 请参见和您可以对要执行的所有可用命令执行for或for each循环:在此循环中,您放置一个try catch,并在catch块中记录/报告异常,但不抛出,以便循环将继续进行下一次

我必须在我的应用程序的一个
sqlcommand
中自动执行多个
sql
insert命令,并且我必须在执行c#的
sqlcommand
中保留无法执行(由于错误)的insert命令。 顺便说一下,我不希望错误阻止继续执行查询

有什么建议吗


谢谢您在SQL语句中使用try-catch


请参阅并使用SQL语句中的try-catch


请参见和

您可以对要执行的所有可用命令执行for或for each循环:在此循环中,您放置一个try catch,并在catch块中记录/报告异常,但不抛出,以便循环将继续进行下一次迭代

请注意,您还可以使用SqlBulk对象以类似于您所描述的方式进行许多插入

编辑:


如果这会减慢速度,您肯定可以使用
SqlBulkCopy
:检查这里的分步示例:

您可以对所有可用命令执行for或for每个循环:在此循环中,您放置一个try catch,并在catch块中记录/报告异常,但不要抛出,这样循环将继续进行下一次迭代

请注意,您还可以使用SqlBulk对象以类似于您所描述的方式进行许多插入

编辑:

如果这会减慢速度,您肯定可以使用
SqlBulkCopy
:检查这里的逐步示例:

这很有效

void ConvertCsv(string sourcePath, string ResultPath)
{


    #region
    using (StreamReader sr = new StreamReader(sourcePath))
    {
        using (StreamWriter sw = new StreamWriter(ResultPath))
        {
            sw.WriteLine(@"DECLARE @er NVARCHAR(MAX)='',@i INT=0 BEGIN  TRY");
            if (sr.Peek() >= 0)
            {
                string currentLine = sr.ReadLine();

                while (currentLine.Trim() == "" && sr.Peek() >= 0)
                    currentLine = sr.ReadLine();
                if (currentLine.Trim() == "")
                {
                    //error :the file is empty
                }
                sw.WriteLine(currentLine);

            }

            while (sr.Peek() >= 0)
            {
                string currentLine = sr.ReadLine();

                if (currentLine.Trim() == "")
                    continue;
                if (currentLine.Trim().StartsWith("INSERT"))
                {
                    while (!currentLine.Trim().StartsWith("INSERT"))
                        currentLine += sr.ReadLine();
                    currentLine = @"END TRY
                                                    BEGIN CATCH
                                                    SELECT @er+=','+LTRIM(RTRIM(STR(ERROR_LINE()))),@i+=1
                                                END CATCH BEGIN  TRY" + Environment.NewLine + currentLine.Trim();

                }
                sw.WriteLine(currentLine.Trim());
            }
            sw.WriteLine(@"END TRY
                                        BEGIN CATCH
                                        SELECT @er+=','+LTRIM(RTRIM(STR(ERROR_LINE())))
                                    END CATCH SELECT @er AS errorLines,@i AS errorCount");
            sw.Close();
            sr.Close();

        }
    }
    #endregion
    ExecuteConvertedFile(ResultPath,Server.MapPath(@"~/Data/Uploads/csv/ErrorLogs/ErrorLog.sql"));
}

void ExecuteConvertedFile(string ResultPath, string errorResultPath)
{
    string wholeQuery = System.IO.File.ReadAllText(ResultPath);
    using (SqlCommand cmd = new SqlCommand { CommandType = CommandType.Text, CommandText = wholeQuery, Connection = new SqlConnection(((SqlConnection)((EntityConnection)new NezaratEntities().Connection).StoreConnection).ConnectionString) })
    {
        cmd.Connection.Open();
        var dr = cmd.ExecuteReader();
        dr.Read();

        WriteErrorLogs(ResultPath,errorResultPath,dr["errorLines"].ToString().Trim());
        Label1.Text = dr["errorCount"].ToString()+"unsuccessful transactions";

    }
}
要保存失败的sql命令,请执行以下操作:

void WriteErrorLogs(string sourcePath, string ResultPath,string errorLinesTolog)
{
    string[] lines = File.ReadAllLines(sourcePath);
    string ErrorLog="";
    errorLinesTolog=errorLinesTolog.Remove(0, 1);

    foreach (var line in errorLinesTolog.Split(','))
    {
        ErrorLog += lines[int.Parse(line)-1] + Environment.NewLine;
    }
    System.IO.File.WriteAllText(ResultPath, ErrorLog);
}
这起作用了

void ConvertCsv(string sourcePath, string ResultPath)
{


    #region
    using (StreamReader sr = new StreamReader(sourcePath))
    {
        using (StreamWriter sw = new StreamWriter(ResultPath))
        {
            sw.WriteLine(@"DECLARE @er NVARCHAR(MAX)='',@i INT=0 BEGIN  TRY");
            if (sr.Peek() >= 0)
            {
                string currentLine = sr.ReadLine();

                while (currentLine.Trim() == "" && sr.Peek() >= 0)
                    currentLine = sr.ReadLine();
                if (currentLine.Trim() == "")
                {
                    //error :the file is empty
                }
                sw.WriteLine(currentLine);

            }

            while (sr.Peek() >= 0)
            {
                string currentLine = sr.ReadLine();

                if (currentLine.Trim() == "")
                    continue;
                if (currentLine.Trim().StartsWith("INSERT"))
                {
                    while (!currentLine.Trim().StartsWith("INSERT"))
                        currentLine += sr.ReadLine();
                    currentLine = @"END TRY
                                                    BEGIN CATCH
                                                    SELECT @er+=','+LTRIM(RTRIM(STR(ERROR_LINE()))),@i+=1
                                                END CATCH BEGIN  TRY" + Environment.NewLine + currentLine.Trim();

                }
                sw.WriteLine(currentLine.Trim());
            }
            sw.WriteLine(@"END TRY
                                        BEGIN CATCH
                                        SELECT @er+=','+LTRIM(RTRIM(STR(ERROR_LINE())))
                                    END CATCH SELECT @er AS errorLines,@i AS errorCount");
            sw.Close();
            sr.Close();

        }
    }
    #endregion
    ExecuteConvertedFile(ResultPath,Server.MapPath(@"~/Data/Uploads/csv/ErrorLogs/ErrorLog.sql"));
}

void ExecuteConvertedFile(string ResultPath, string errorResultPath)
{
    string wholeQuery = System.IO.File.ReadAllText(ResultPath);
    using (SqlCommand cmd = new SqlCommand { CommandType = CommandType.Text, CommandText = wholeQuery, Connection = new SqlConnection(((SqlConnection)((EntityConnection)new NezaratEntities().Connection).StoreConnection).ConnectionString) })
    {
        cmd.Connection.Open();
        var dr = cmd.ExecuteReader();
        dr.Read();

        WriteErrorLogs(ResultPath,errorResultPath,dr["errorLines"].ToString().Trim());
        Label1.Text = dr["errorCount"].ToString()+"unsuccessful transactions";

    }
}
要保存失败的sql命令,请执行以下操作:

void WriteErrorLogs(string sourcePath, string ResultPath,string errorLinesTolog)
{
    string[] lines = File.ReadAllLines(sourcePath);
    string ErrorLog="";
    errorLinesTolog=errorLinesTolog.Remove(0, 1);

    foreach (var line in errorLinesTolog.Split(','))
    {
        ErrorLog += lines[int.Parse(line)-1] + Environment.NewLine;
    }
    System.IO.File.WriteAllText(ResultPath, ErrorLog);
}

请告诉我们你做了什么already@pinusnegra请告诉我们你做了什么already@pinusnegra:大约什么都没有什么慢的是什么?你能在句子中多写一些单词吗?在c#的循环中尝试查询并捕捉每一行的错误太慢了,因为我有35179行,每一行都是一个单独的insertwhat是慢的?你能在你的句子中多写一些单词吗?如果我有35179行,每行都是一个插入,那么在c#的循环中尝试查询并捕捉每行的错误太慢了