1. 程式人生 > >c#讀取txt檔案並匯入到資料庫

c#讀取txt檔案並匯入到資料庫

這是一個ado.net和檔案操作相結合的一個例子,比較經典哦。做的過程中出現了好多問題最終還是做出來了,學習的確需要別人的幫助,如果別人有問題了不管多忙都先學著去幫助別人,因為你要相信你並不是什麼都會。學習相互提高才是最好的狀態。做這個小例子我問了一個網上的“高手”他卻騙我說在加班,不幫我解決問題。強烈鄙視這類人,不是熟人就不能問問題了嗎?讓這些人見鬼去吧。

我先貼程式碼啊,後面再給大家說我遇到的問題

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 nybutton_Click(object sender, EventArgs e)
        {
            if(myimport.ShowDialog()!=DialogResult.OK){
                return;
            }
            //使用FileStream讀取檔案
           FileStream fileStream = File.OpenRead(myimport.FileName);



           SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=g:\vsworkspace\檔案的匯入\檔案的匯入\hnspi.mdf;Integrated Security=True;User Instance=True");




               StreamReader reader = new StreamReader(fileStream);
                 

                        conn.Open();
                        //向資料庫插入資料  
                       SqlCommand command = conn.CreateCommand();
                      
                            command.CommandText = "insert into student (sno,sname) values (@Sno,@Sname)";
                            string line = null;
                            while ((line = reader.ReadLine())!= null)
                            {
                                string[] str = line.Split(',');

                                string num = str[0];
                                string name= str[1];
                                command.Parameters.Clear(); //每次插入都要清除引數
                                command.Parameters.Add(new SqlParameter("Sno", num));
                                command.Parameters.Add(new SqlParameter("Sname", name));
                                //int tem=command.ExecuteNonQuery();
                             
                                if (command.ExecuteNonQuery() > 0)

                                {
                                    MessageBox.Show("1條資料儲存成功");
                                }
                                //MessageBox.Show(command.ExecuteNonQuery().ToString());
                            }
                         
                          fileStream.Close();
                          reader.Close();
                          conn.Dispose();
                          
                        }

                      
                   
                  }
            }
            
           // MessageBox.Show("資料儲存成功");
           
   

我做的時候遇到了這2個問題

1.連線字串不對,在這裡可以把它複製過來,就是右擊資料連線下面的mdf檔案,找到屬性

2.插入的時候沒有clear引數,這個問題是最容易出現的

程式中的東西的確需要仔細琢磨,遇到問題了不要輕易放棄。因為我也是在百度裡找了好幾十頁的連線才找到解決方法的。希望能夠和大家分享我的程式碼和開發經驗。