本帖最后由 吴春晟 于 2011-11-15 13:14 编辑
我在做手机号码归属地查询这个练习时,进行多文件批量导入
代码如下:- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Data.SqlClient;
- namespace 手机号码归属地查询
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- //private static string filePath;
- private static string[] filelists;
- private void button1_Click(object sender, EventArgs e)
- {
- if (ofdFilelist.ShowDialog() == DialogResult.OK)
- {
- filelists = ofdFilelist.FileNames;
- for (int i = 0; i < filelists.Length; i++)
- {
- FileInfo fileinfo = new FileInfo(filelists[i]);
- ltbFile.Items.Add(fileinfo.Name.Remove(fileinfo.Name.LastIndexOf(".")));
- }
- }
- }
- private void btnUpdate_Click(object sender, EventArgs e)
- {
- using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLSERVER_WCS;AttachDbFilename=|DataDirectory|\DBPhoneNO.mdf;Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- foreach (string file in filelists)
- {
- FileInfo fileinfo = new FileInfo(file);
- string str = fileinfo.Name.Remove(fileinfo.Name.LastIndexOf("."));
- using (FileStream filestream = File.OpenRead(file))
- {
- using (StreamReader streamreader = new StreamReader(filestream, System.Text.Encoding.Default))
- {
- string line = null;
- while (((line = streamreader.ReadLine()) != null))
- {
- string[] strs = line.Split('-');
- string phoneNOStart = strs[0];
- string phoneNOEnd = strs[1];
- string city = strs[2];
- cmd.CommandText += "insert into T_PhoneNO(PhoneNOStart,PhoneNOEnd,City,PromaryAndNet) values(@PhoneNOStart,@PhoneNOEnd,@City,@PromaryAndNet)";
- cmd.Parameters.Clear();//!!!!!!SQL参数不能重复添加,在while中一直用的是同一个SqlCommand对象;
- cmd.Parameters.Add(new SqlParameter("PhoneNOStart", phoneNOStart));
- cmd.Parameters.Add(new SqlParameter("PhoneNOEnd", phoneNOEnd));
- cmd.Parameters.Add(new SqlParameter("City", city));
- cmd.Parameters.Add(new SqlParameter("PromaryAndNet", str));
- cmd.ExecuteNonQuery();
- }
- }
- }
- }
- }
- }
- MessageBox.Show("数据导入成功");
- }
- }
- }
复制代码 在导入数据时 效率很差,一个900多行的 文本文件在导入就要用时 10多分钟,而且可能会报错。应该如何进行优化??
再查看数据库数据,发现明明只有900多行数据 在数据库里插入了 10多W条,怪不得速度慢得要命,哪出了问题??
界面如下:
|
|