当前位置:Gxlcms > 数据库问题 > C/s从文件(TXT)中读取数据插入数据库

C/s从文件(TXT)中读取数据插入数据库

时间:2021-07-01 10:21:17 帮助过:50人阅读

流程:

1.当按钮单击时,弹出OpenFileDialog

2.判断后缀名是否合法

3.导入数据库

 

按钮事件中的代码:

1.判断用户是否选中文件。

2.判断用户选择的文件是否为txt

  1. //第一步,当按钮被点击时,弹出选择文件框,OpenFileDialog
  2. OpenFileDialog ofd = new OpenFileDialog();
  3. ofd.Filter = "文件文件|*.txt";
  4. if (ofd.ShowDialog() == DialogResult.OK)
  5. {
  6. if (ofd.SafeFileName == "*.txt")
  7. {
  8. this.txtFilePath.Text = ofd.FileName;
  9. //准备导入数据
  10. ImportData(ofd.FileName);
  11. }
  12. }

  

ImportData中的代码:

*:这种方式可以节省打开服务器连接的效率,不用没执行一次循环就开启一次连接。

1.打开reader流,并制定文件编码格式,这里给的是本机编码,Encoding.Default

2.以约定的分隔符分割文件,这里是用,作为分隔符

3.拼接插入数据库的Sql语句

4.执行sql代码。

  1. private void ImportData(string Path)
  2. {
  3. string temp = string.Empty;
  4. //File.ReadAllText(Path);
  5. using (StreamReader reader = new StreamReader(Path,Encoding.Default)) //指定编码格式,如果指定的文件编码格式不一样则会乱码
  6. {
  7. //reader.ReadLine();
  8. string connStr = ConfigurationManager.ConnectionStrings["SqlConfig"].ConnectionString;
  9. using (SqlConnection conn = new SqlConnection(connStr))
  10. {
  11. conn.Open();
  12. //using (SqlCommand cmd = new SqlCommand(sql,conn))
  13. using (SqlCommand cmd = conn.CreateCommand())
  14. {
  15. while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
  16. {
  17. var ss = temp.Split(‘,‘); //,为约定的分隔符,当前ss中存储的是已经分割后的数组
  18. 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语句,数值类型需要+‘’
  19. conn.Open();
  20. cmd.CommandText = sql;
  21. cmd.ExecuteNonQuery();
  22. }//end while
  23. }//end SqlCommand
  24. }//end SqlConnection
  25. }//end StreamReader
  26. }

  

C/s从文件(TXT)中读取数据插入数据库

标签:类型   led   dial   .exe   连接   .com   oid   事件   student   

人气教程排行