用excel导入用户到数据库中,一两秒导入几千条数据感觉非常快,但是这是一条条的插入到数据库的。在做select
*的时候,数据是一条条的插入的吗?用一个datatable保存所有查询的数据返回给客户端。
大量数据的导入也是这样的。把很多数据保存到table中然后保存table就可以了。
首先看一下怎么打开资源库并且把选中的路径放到文本框,并且寻找文本文档。
using (OpenFileDialog ofd=new OpenFileDialog())//资源 { ofd.Filter = "文本文档|*.txt";//筛选文章类别 if (ofd.ShowDialog()==DialogResult.OK)//选中 { txtImport.Text = ofd.FileName;//将选择的文本地址赋值 IMportData(ofd.FileName); } }
文本文档的数据读取,表的建立,初始化,绑定数据,插入
string temp = string.Empty; //读取文件的名称 using (StreamReader reader = new StreamReader(FileName,Encoding.UTF8)) { reader.ReadLine();//去掉第一行 //读取配置文件 string connstr = ConfigurationManager.ConnectionStrings["sql2"].ConnectionString; //新建,初始化表,表格中的数据要和数据库中的类型一致,字段名也要相同 DataTable once_Sockdetailhistory = new DataTable(); once_Sockdetailhistory.Columns.Add("SockNumber", typeof(int)); once_Sockdetailhistory.Columns.Add("Scokintotime", typeof(DateTime)); once_Sockdetailhistory.Columns.Add("Sockintopeople", typeof(string)); once_Sockdetailhistory.Columns.Add("SockID", typeof(string)); once_Sockdetailhistory.Columns.Add("SockdetailhistoryID", typeof(string)); using (SqlConnection conn=new SqlConnection(connstr)) { //using (SqlCommand cmd=conn.CreateCommand()) //{ conn.Open(); while (!string.IsNullOrEmpty(temp = reader.ReadLine())) { var strs = temp.Split(','); //string sql = string.Format("insert into Sockdetailhistory(SockNumber,Sockintopeople,SockID) values('{0}','{1}','{2}')", strs[0],strs[1], strs[4]); //cmd.CommandText = sql; //cmd.ExecuteNonQuery(); //表格填充,创建新的一行,逐行赋值 DataRow newrow = once_Sockdetailhistory.NewRow(); newrow["SockNumber"] = strs[0]; newrow["Sockintopeople"] = strs[1]; newrow["SockID"] = strs[4]; //把这一行添加到表中 once_Sockdetailhistory.Rows.Add(newrow); } addDatatabletosql(once_Sockdetailhistory,conn); //} } }
private void addDatatabletosql(DataTable once_Sockdetailhistory,SqlConnection thisconn) { using (SqlBulkCopy bulkcopy=new SqlBulkCopy(thisconn))//相当于sqlcommand { bulkcopy.DestinationTableName = "Sockdetailhistory"; //数据表 bulkcopy.WriteToServer(once_Sockdetailhistory); } }