c#读取txt文件并导入到数据库

这是一个ado.net和文件操作相结合的一个例子,比较经典哦。做的过程中出现了好多问题最终还是做出来了,学习的确需要别人的帮助,如果别人有问题了不管多忙都先学着去帮助别人,因为你要相信你并不是什么都会。学习相互提高才是最好的状态。做这个小例子我问了一个网上的“高手”他却骗我说在加班,不帮我解决问题。强烈鄙视这类人,不是熟人就不能问问题了吗?让这些人见鬼去吧。

我先贴代码啊,后面再给大家说我遇到的问题

 

  1.  
    using System;
  2.  
    using System.Collections.Generic;
  3.  
    using System.ComponentModel;
  4.  
    using System.Data;
  5.  
    using System.Drawing;
  6.  
    using System.Linq;
  7.  
    using System.Text;
  8.  
    using System.Windows.Forms;
  9.  
    using System.IO;
  10.  
    using System.Data.SqlClient;
  11.  
     
  12.  
    namespace 文件的导入
  13.  
    {
  14.  
    public partial class Form1 : Form
  15.  
    {
  16.  
    public Form1()
  17.  
    {
  18.  
    InitializeComponent();
  19.  
    }
  20.  
     
  21.  
    private void nybutton_Click(object sender, EventArgs e)
  22.  
    {
  23.  
    if(myimport.ShowDialog()!=DialogResult.OK){
  24.  
    return;
  25.  
    }
  26.  
    //使用FileStream读取文件
  27.  
    FileStream fileStream = File.OpenRead(myimport.FileName);
  28.  
     
  29.  
     
  30.  
     
  31.  
    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=g:\vsworkspace\文件的导入\文件的导入\hnspi.mdf;Integrated Security=True;User Instance=True");
  32.  
     
  33.  
     
  34.  
     
  35.  
     
  36.  
    StreamReader reader = new StreamReader(fileStream);
  37.  
     
  38.  
     
  39.  
    conn.Open();
  40.  
    //向数据库插入数据
  41.  
    SqlCommand command = conn.CreateCommand();
  42.  
     
  43.  
    command.CommandText = "insert into student (sno,sname) values (@Sno,@Sname)";
  44.  
    string line = null;
  45.  
    while ((line = reader.ReadLine())!= null)
  46.  
    {
  47.  
    string[] str = line.Split(',');
  48.  
     
  49.  
    string num = str[0];
  50.  
    string name= str[1];
  51.  
    command.Parameters.Clear(); //每次插入都要清除参数
  52.  
    command.Parameters.Add(new SqlParameter("Sno", num));
  53.  
    command.Parameters.Add(new SqlParameter("Sname", name));
  54.  
    //int tem=command.ExecuteNonQuery();
  55.  
     
  56.  
    if (command.ExecuteNonQuery() > 0)
  57.  
     
  58.  
    {
  59.  
    MessageBox.Show("1条数据保存成功");
  60.  
    }
  61.  
    //MessageBox.Show(command.ExecuteNonQuery().ToString());
  62.  
    }
  63.  
     
  64.  
    fileStream.Close();
  65.  
    reader.Close();
  66.  
    conn.Dispose();
  67.  
     
  68.  
    }
  69.  
     
  70.  
     
  71.  
     
  72.  
    }
  73.  
    }
  74.  
     
  75.  
    // MessageBox.Show("数据保存成功");
  76.  
     
  77.  
     

 

我做的时候遇到了这2个问题

1.连接字符串不对,在这里可以把它复制过来,就是右击数据连接下面的mdf文件,找到属性

2.插入的时候没有clear参数,这个问题是最容易出现的

 

程序中的东西的确需要仔细琢磨,遇到问题了不要轻易放弃。因为我也是在百度里找了好几十页的连接才找到解决方法的。希望能够和大家分享我的代码和开发经验。

posted @ 2018-09-06 14:32  net5x  阅读(1509)  评论(0)    收藏  举报