string str = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;//写在配置文件里面的链接数据库语句
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "文本文件|*.txt";
if (ofd.ShowDialog() != true)
return;
//using (FileStream fs = File.OpenRead(ofd.FileName))
//using (StreamReader sr = new StreamReader(fs, Encoding.Default))
// while (sr.ReadLine() != null)
// { }
string[] linesArr = File.ReadLines(ofd.FileName, Encoding.Default).ToArray();
DataTable table = new DataTable();
table.Columns.Add("Num");//创建列名
table.Columns.Add("Area");
table.Columns.Add("Type");
//向本地table中插入内容
for (int i = 1; i < linesArr.Length; i++)
{
string[] lineArr = linesArr[i].Split('\t');
string startTelNum=lineArr[0];
string city=lineArr[1];
city = city.Trim('"');
string type=lineArr[2];
type = type.Trim('"');
DataRow row = table.NewRow();//创建一个行的对象
row["Num"] = startTelNum;//向行里面插入数据
row["Area"] = city;
row["Type"] = type;
table.Rows.Add(row);//向表里插入一行
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(str))
{
bulkCopy.DestinationTableName = "T_TelNum";
//创建和数据库的映射关系,一对一Copy
bulkCopy.ColumnMappings.Add("Num","StartTelNum");
bulkCopy.ColumnMappings.Add("Area","TelArea");
bulkCopy.ColumnMappings.Add("Type","TelType");
bulkCopy.WriteToServer(table);
}
MessageBox.Show("导入成功!");
}
SQLBulkCopy,用于数据库之间大批量的数据传递。 |
|