net 单文件导入


 

 

 

       private void button1_Click(object sender, EventArgs e)  // 在button1事件中弹出filesname
        {
            if (filesname.ShowDialog() != DialogResult.OK) //如果showdialog打开的时候
            {
           
           
            }
            else
            {   using (FileStream fileStream = File.OpenRead(filesname.FileName))   //  申明一个Filestream变量 来读取打开的这个文件

            {

                using (StreamReader streamReader = new StreamReader(fileStream))  //StreamReader来读取这个filestream
                {


                    using (SqlConnection sqlcon = new SqlConnection("data source=.;database=csstsale;user=sa ;pwd=csst")) //建立数据库连接
                    {
                        sqlcon.Open();


                        using (SqlCommand cmd = sqlcon.CreateCommand())
                        {

                            string line = null;

                            cmd.CommandText = "insert into inputfile (name,age)values(@username,@age)"; 

                            while ((line = streamReader.ReadLine()) != null)  //如过不等于空 一直读取下去
                            {

                                string[] strs = line.Split('|');  //用|来分割字符串分配到strs[] 数组当中

                                string name = strs[0];   //分割的两个参数

                                int age = Convert.ToInt32(strs[1]);//转换分割的第二个参数

                                cmd.Parameters.Clear();//清楚parameters[]变量

                                cmd.Parameters.Add(new SqlParameter("Name", name));// 添加

                                cmd.Parameters.Add(new SqlParameter("Age", age));//

                                cmd.ExecuteNonQuery();  //执行cmd

                            }


                        }
                    }
                }
               
               
                }
           
           
            }


        }

 

 

  

你可能感兴趣的:(net 单文件导入)