SqlBulkCopy导入大数据
本次导入的为手机号码归属地数据:
建立一个数据库Area,表phone,表中三个字段startNo,endNo,cityName
string connStr = ConfigurationManager.ConnectionStrings["connStr"].ToString();FolderBrowserDialog openfile = new FolderBrowserDialog();
if (openfile.ShowDialog() != DialogResult.OK)
{
return;
}string path = openfile.SelectedPath;
List<string> list = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).ToList();
foreach (string file in list){
string name = Path.GetFileNameWithoutExtension(file);string[] lines = File.ReadAllLines(file, Encoding.Default); //在内存中建立一个表DataTable table = new DataTable(); //创建一个表后要先创建列,再创建行table.Columns.Add("startTelNum"); table.Columns.Add("endTelNum");table.Columns.Add("cityName");foreach (string line in lines){
string[] strs = line.Split('-');string startTelNum = strs[0]; string endTelNum = strs[1];string cityName = strs[2];DataRow row = table.NewRow();
row["startTelNum"] = startTelNum; row["endTelNum"] = endTelNum;row["cityName"] = cityName; table.Rows.Add(row); }using (SqlBulkCopy bulkcopy = new SqlBulkCopy(connStr)){
bulkcopy.DestinationTableName = "phone";//服务器上表的名称bulkcopy.ColumnMappings.Add("startTelNum", "startNo");//前面参数是内存中表名称,后面是数据库字段名称bulkcopy.ColumnMappings.Add("endTelNum", "endNo");bulkcopy.ColumnMappings.Add("cityName", "cityName");bulkcopy.WriteToServer(table);//把数据写入到数据库 }数据库下载:Download