C#Winform向数据库中导入.txt或者.CSV文件的数据

 protected void ImportData(string filePath)
        {
            if (filePath.Length == 0)
            {
                MessageBox.Show("请选择要导入的txt文件");
            }

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    //不读第一行的标题咧
                    sr.ReadLine();

                    string row_text = "";
                    string Exceptions = "";

                    List<string> sqlList = new List<string>();

                    while ((row_text = sr.ReadLine()) != null)
                    {
                        string[] datas = row_text.Split(',');
                        string sql = "insert into room (roomid,typeids,price,status,isdeleted ) values ('" + datas[0] + "'," + datas[1] + "," + datas[2] + "," + datas[3] + "," + datas[4] + ")";
                        sqlList.Add(sql);
                    }
                    try
                    {
                        DBUtil.ExSqlList(sqlList, out Exceptions);
                                                
                        MessageBox.Show("导入数据成功,共导入行数:" + sqlList.Count.ToString());
                    }
                    catch (Exception ex)
                    {
                        Exceptions = ex.Message.ToString();
                        MessageBox.Show("导入数据出错,错误信息:" + Exceptions);
                    }
                }
            }
        }
下面给出向数据库中批量插入数据的DBUtil中的ExSqlList方法
  public static bool ExSqlList(List<string > sqlList,out string exceptions)
        {

            exceptions = "";

            bool isSuccess = true;

            using (SqlConnection conn = new SqlConnection(sqlconn))
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand();

                SqlTransaction trans = conn.BeginTransaction();

                cmd.Connection = conn;

                cmd.Transaction = trans;

                try
                {
                    foreach (string sql in sqlList)
                    {
                        cmd.CommandText = sql;

                        cmd.ExecuteNonQuery();
                    }

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    trans.Rollback();
                    exceptions = ex.Message.ToString();
                    throw new ApplicationException(exceptions);
                }
                return isSuccess;
            }
        }

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值