关于以DataTable形式批量写入数据的案例
//批量添加数据交互ADO.NET部分
void IDataAccess.CommandDataTable(DataTable dt, string ProcedureName, System.Data.Common.DbParameter[] para) { _sqlConnection = new SqlConnection(strConnet); SqlDataAdapter MyAdapter = new SqlDataAdapter(); MyAdapter.InsertCommand = new SqlCommand(); MyAdapter.InsertCommand.CommandType = CommandType.StoredProcedure; MyAdapter.InsertCommand.CommandText = ProcedureName; MyAdapter.InsertCommand.Connection = _sqlConnection; foreach (SqlParameter parm in para) MyAdapter.InsertCommand.Parameters.Add(parm); MyAdapter.Update(dt); if (_sqlConnection != null) { _sqlConnection.Close(); } GC.Collect(); } //创建要添加的批量数据Table public System.Data.DataTable CreateCartTable() { System.Data.DataTable dt = new System.Data.DataTable(); System.Data.DataRow dr; dt.Columns.Add(new System.Data.DataColumn("UserID")); dt.Columns.Add(new System.Data.DataColumn("ProductID")); dt.Columns.Add(new System.Data.DataColumn("Count")); IDataReader reader = new MssqlDataReader(); string[] s = Request.QueryString["ids"].ToString().Split(new char[] { ',' }); if (s != null && s.Length > 0) { for (int i = 0; i < s.Length; i++) { TempCart[] tc = reader.GetTempCartByID(Convert.ToInt32(s[i])); if (tc.Length > 0) { dr = dt.NewRow(); dr[0] = Session["ID_Member"].ToString(); dr[1] = tc[0].ProductID.ToString(); dr[2] = tc[0].Count.ToString(); dt.Rows.Add(dr); } } } return dt; } //调用批量添加的方法 void IDataWriter.AddCartMore(DataTable dt) { IDataAccess access = DataCenter.GetDbConnection(); SqlParameter[] para ={ new SqlParameter("@UserID",SqlDbType.Int), new SqlParameter("@ProductID",SqlDbType.Int), new SqlParameter("@Count",SqlDbType.Int) }; para[0].SourceColumn = dt.Columns[0].ColumnName; para[1].SourceColumn = dt.Columns[1].ColumnName; para[2].SourceColumn = dt.Columns[2].ColumnName; access.CommandDataTable(dt, "Sy_Cart_Add", para); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步