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
        }