[英]Bulk Data extraction to DB File in C#
我有大量数据说记事本文件中有45,000万行数据,
我把那个获取的文件分割成小文件,
我的数据如下:
('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());
}
}
}
}
提前致谢
我要做的是为您的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 { }
块中查看有关如何处理INSERT错误的评论
通过具有try/catch
周围ExecuteNonQuery()
调用,你必须在其上的颗粒问题INSERT
语句失败,以及与错误的特定异常。 这样做的另一个好处是,它将允许您继续执行而不是将异常冒泡到外部try/catch
逻辑。 当然,除非您要停止执行,否则可以从内部catch { }
块中抛出异常。 这完全取决于您要如何处理故障。
注意:对于外部try/catch
块,应包括一个finally { }
,在其中调用SqlConnection.Dispose()
以释放连接并处置对象( cn.Dispose()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.