private string connStr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
/// <summary>
/// 用insert方法从文本文件中批量导入到数据库表中
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "文本文档|*.txt";
//如果用户没有选择文件并确定则直接返回
if (ofd.ShowDialog() != true)
{
return;
}
//获得文件名包括路径
string fileName = ofd.FileName;
try
{
//定义一个开始时间
DateTime startTime = DateTime.Now;
//因为文件比较大,所有使用StreamReader的效率要比使用File.ReadLines高
using (StreamReader sr = new StreamReader(fileName, Encoding.Default))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
while (!sr.EndOfStream)
{
string readStr = sr.ReadLine();//读取一行数据
if (readStr.StartsWith("1"))//去掉标题行
{
string[] strs = readStr.Split(new char[] { '\t', '"' }, StringSplitOptions.RemoveEmptyEntries);//将读取的字符串按"制表符/t“和””“分割成数组
string startNum = strs[0];
string numArea = strs[1];
string numType = strs[2];
cmd.CommandText = "insert into T_PhoneInfo(FStartNum,FNumArea,FNumType) values(@startNum,@numArea,@numType)";
cmd.Parameters.Clear();//清除上一次的参数
cmd.Parameters.Add(new SqlParameter("@startNum", startNum));
cmd.Parameters.Add(new SqlParameter("@numArea", numArea));
cmd.Parameters.Add(new SqlParameter("@numType", numType));
cmd.ExecuteNonQuery();
}
}
}
}
}
//结束时间-开始时间=总共花费的时间
TimeSpan ts = DateTime.Now - startTime;
MessageBox.Show("导入数据成功!共花费时间:" + ts.ToString());
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
追问![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/a8773912b31bb0511816991f3d7adab44aede0d3?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
大神报错了