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 void btnImport_Click(object sender, EventArgs e)
{
if (ofdImport.ShowDialog() != DialogResult.OK)
{
return;
}
//打开现有文件以进行读取
//using (FileStream fileStream = new FileStream(ofdImport.FileName, FileMode.Open,
// FileAccess.Read,FileShare.None))
using (FileStream fileStream = File.OpenRead(ofdImport.FileName))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDBFilename=" +
AppDomain.CurrentDomain.BaseDirectory + "Phone.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
//创建连接非常耗时,因此不要每次操作都创建连接
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Insert into T_PhoneNum(StartNo,EndNo,Sheng,Shi,TMobile,CardType)values(@StartNo,@EndNo,@Sheng,@Shi,@TMobile,@CardType)";
string line = null;
while ((line = streamReader.ReadLine()) != null)//先在()中给line赋值,然后再进行比较
{
string[] strs = line.Split('-');
string startNo = strs[0];
string endNo = strs[1];
string sheng = strs[2];
string shi = strs[3];
string merchant = strs[4];
string type = strs[5];
//参数不能重复添加,在while中一直用的就是同一个SqlCommand对象
cmd.Parameters.Clear();//每次添加参数前先清除原先上次执行的参数
cmd.Parameters.Add(new SqlParameter("StartNo", startNo));
cmd.Parameters.Add(new SqlParameter("EndNo", endNo));
cmd.Parameters.Add(new SqlParameter("Sheng", sheng));
cmd.Parameters.Add(new SqlParameter("Shi", shi));
cmd.Parameters.Add(new SqlParameter("TMobile", merchant));
cmd.Parameters.Add(new SqlParameter("CardType", type));
cmd.ExecuteNonQuery();//假如不清空原先数据,在此会出现SqlException异常(变量名'@Name'已声明)
}
}
}
}
}
MessageBox.Show("数据导入成功!");
}
}
}
|