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


    流程:

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

    2.判断后缀名是否合法

    3.导入数据库

    按钮事件中的代码:

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

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

    //第一步,当按钮被点击时,弹出选择文件框,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中的代码:

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

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

    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
            }
    

      

    感谢着知识大爆炸的时代,感谢这人人共享的精神
  • 相关阅读:
    mobilebone.js使用笔记
    js笔记:匿名函数
    java中==和equals和hashcode的区别详解
    JVM基础学习之基本概念、可见性与同步
    面向对象-抽象类和接口解析
    maven使用deploy发布到本地仓库
    Jackson 时间格式化,时间注解 @JsonFormat 与 @DatetimeFormat 用法、时差问题说明
    cxf动态调用webservice设置超时,测试线程安全
    再谈API GateWay服务网关
    微服务实战-使用API Gateway
  • 原文地址:https://www.cnblogs.com/Zhang-silence/p/6475762.html
Copyright © 2020-2023  润新知