【问题标题】:Bulk Data extraction to DB File in C#在 C# 中将批量数据提取到 DB 文件
【发布时间】:2015-07-30 17:50:52
【问题描述】:

我在记事本文件中有大量数据,例如 45,00,000 行数据,
我把那个gaint文件分成小文件,
我的数据如下:

('1','dsamp','tty','tmp'....)
and so on

现在我正在逐个读取文件并使用插入脚本和一段 C# 代码将它们写入 .mdf 文件,但是当我遇到一些错误时,我无法找到错误的位置,我想要从头开始并从第 0 行插入。
有没有最好的方法或代码或工具来做到这一点 我的代码如下所示

    private void Form1_Load(object sender, EventArgs e)
    {
        int i = 0;
        try
        {
            string const_state = "INSERT INTO Authors1 VALUES";
            string conn = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\srikanth\documents\visual studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\SampleDB.mdf;Integrated Security=True;Connect Timeout=30";
            SqlConnection cn = new SqlConnection(conn);
            cn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            string line;

            System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\Public\\New1.txt");
            while ((line = file.ReadLine()) != null)
            {
                line = line.Trim();
                line = line.TrimEnd(',', ',',',', '.');
                cmd.CommandText = const_state + line+";";
                cmd.ExecuteNonQuery();
                i++;
            }
            MessageBox.Show(i.ToString());

            file.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(i.ToString());
            MessageBox.Show(ex.ToString());
        }

    }
}

}


提前致谢

【问题讨论】:

  • 你能告诉我们你的代码吗?听起来您只需要重新处理错误处理以更好地了解故障(即哪个文件包含故障数据,故障是什么等)。

标签: c# sql insert mdf


【解决方案1】:

我要做的是为您的ExecuteNonQuery() 呼叫设置一个try/catch 块。像这样的:

        while ((line = file.ReadLine()) != null)
        {
            line = line.Trim();
            line = line.TrimEnd(',', ',',',', '.');
            cmd.CommandText = const_state + line+";";
            try 
            {
                cmd.ExecuteNonQuery();
            }
            catch
            {
                // dump cmd.CommandText somewhere as well as 
                // the actual exception details
                //
                // that'll give you two things: 1) the specific 
                // issue, and 2) the actual INSERT statement that 
                // failed
            }
            i++;
        }

catch { } 块中查看我的 cmets,了解我将如何处理 INSERT 错误

通过在ExecuteNonQuery() 调用周围使用try/catch,您将遇到which INSERT 语句失败的具体问题,以及带有错误的特定异常。这样做的另一个好处是它允许您继续执行,而不是将异常冒泡到外部 try/catch 逻辑。当然,除非您想停止执行,在这种情况下,您可以从内部 catch { } 块中重新抛出异常。这完全取决于您希望如何处理故障。

注意:对于您的外部 try/catch 块,您应该包含一个 finally { },您可以在其中调用 SqlConnection.Dispose() 以释放连接并处置对象 (cn.Dispose())。

【讨论】:

  • 是的,这应该可以解决错误问题,时间呢,读取 45,00,000 行将是一项繁重的工作,是否也有解决方案?
  • @SrikanthSuryadevara 您是指从文本文件中读取数据的持续时间,还是将数据插入数据库表的持续时间?
  • 从文本文件中读取+写入数据库
猜你喜欢
  • 2011-09-17
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多