C/s從文件(TXT)中讀取數據插入數據庫

流程:sql

1.當按鈕單擊時,彈出OpenFileDialog數據庫

2.判斷後綴名是否合法數組

3.導入數據庫服務器

 

按鈕事件中的代碼:this

1.判斷用戶是否選中文件。編碼

2.判斷用戶選擇的文件是否爲txtorm

//第一步,當按鈕被點擊時,彈出選擇文件框,OpenFileDialog
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "文件文件|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
if (ofd.SafeFileName == "*.txt")
{
this.txtFilePath.Text = ofd.FileName;
//準備導入數據
ImportData(ofd.FileName);
}
}

  

ImportData中的代碼:blog

*:這種方式能夠節省打開服務器鏈接的效率,不用沒執行一次循環就開啓一次鏈接。事件

1.打開reader流,並制定文件編碼格式,這裏給的是本機編碼,Encoding.Defaultcmd

2.以約定的分隔符分割文件,這裏是用,做爲分隔符

3.拼接插入數據庫的Sql語句

4.執行sql代碼。

private void ImportData(string Path)
        {
            string temp = string.Empty;
            //File.ReadAllText(Path);
            using (StreamReader reader = new StreamReader(Path,Encoding.Default)) //指定編碼格式,若是指定的文件編碼格式不同則會亂碼
            {
                //reader.ReadLine();
                string connStr = ConfigurationManager.ConnectionStrings["SqlConfig"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    //using (SqlCommand cmd = new SqlCommand(sql,conn))
                    using (SqlCommand cmd = conn.CreateCommand())
                    {

                        while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
                        {
                            var ss = temp.Split(',');   //,爲約定的分隔符,當前ss中存儲的是已經分割後的數組
                            string sql = string.Format("insert into tblStudent(stuName,stuSex,stuBirthDate,stuPhone) values({0},{1},{2},{3},{4})", ss[0], ss[1], ss[2], ss[3]); //拼接Sql語句,數值類型須要+‘’
                            conn.Open();
                            cmd.CommandText = sql;
                            cmd.ExecuteNonQuery();
                        }//end while
                    }//end SqlCommand
                }//end SqlConnection
            }//end StreamReader
        }
相關文章
相關標籤/搜索