【ADO.NET】3、从TXT中导入数据到数据库

复制代码
private void btnInput_Click(object sender, EventArgs e)
 {
    if (opFile.ShowDialog() != DialogResult.OK)    //判断用户点击 确定 还是 取消,不点确定,则返回程序
     {
           return;
     }
     using(FileStream FStream = File.OpenRead(opFile.FileName))        //打开文件进行读取
     {
        //定义字符编码为GB2312
        using (StreamReader stremReader = new StreamReader(FStream,Encoding.GetEncoding("GB2312")))    
      {
        using (SqlConnection conn = new SqlConnection(@"server=.;database=mytest;uid=sa;pwd=gao"))
          {
             conn.Open();
             using (SqlCommand cmd = conn.CreateCommand())
             {
               cmd.CommandText = "insert into T_Age(Name,Age) values(@N,@A)";
               string line = null;

               while ((line = stremReader.ReadLine()) != null)    //读取文本中一行数据,当不为空时
               {
                 string[] strs = line.Split('-');        // 按"-"符分割字符串
                 string name = strs[0];
                 int age = Convert.ToInt32(strs[1]);
                 cmd.Parameters.Clear(); //参数不能重复添加,在while中一直用的是这个SqlCommand对象
              cmd.Parameters.Add(new SqlParameter("@N", name));
                 cmd.Parameters.Add(new SqlParameter("@A", age));
                 cmd.ExecuteNonQuery();
                 }
               }
           }
      }
        MessageBox.Show("导入成功!");
     } 
 }
复制代码
posted on 2017-05-11 21:09 叶祖辉 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/yezuhui/p/6842797.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值