DataAdapter.Update 批量插入的数据每个字段都为0,请高人指点一下,谢谢!
确认不明白为何是这样!
测试代码如下:(da我是封装的一个类似SQLHelper类)
var srcTable = da.ExecuteDataTable(@"DECLARE @n INT; DECLARE @t TABLE(Name NVARCHAR(50),Age INT,Remark NVARCHAR(50)) SET @n=1;WHILE (@n<=100)BEGIN INSERT INTO @t VALUES( N'中国人' + CONVERT(NVARCHAR(10),@n),@n+10,N'仅供测试'); SET @n=@n+1; END SELECT * FROM @t;"); var sqlParams = da.ParameterHelper.AddParameter("@Name", DbType.String, "Name", 50).AddParameter("@Age", DbType.Int32, "Age").AddParameter("@Remark", DbType.String, "Remark", 50).ToParameterArray(); BatchExecuteCommand("INSERT INTO dbo.T_TestPeople(Name,Age,Remark) VALUES(@Name,@Age,@Remark)", sqlParams, srcTable); //我写的一个通用批量执行的方法 public int BatchExecuteCommand(string sqlCmdText, object[] paramObjs, DataTable srcTable, int batchSize = 0) { var dbCmd = BuildDbCommand(sqlCmdText, CommandType.Text, paramObjs); dbCmd.UpdatedRowSource = System.Data.UpdateRowSource.None; var dbAdapter = dbProviderFactory.CreateDataAdapter(); sqlCmdText = sqlCmdText.Trim(); string bathExecType = System.Text.RegularExpressions.Regex.Match(sqlCmdText, @"^\w+\b").Value.ToUpper(); switch (bathExecType) { case "INSERT": { dbAdapter.InsertCommand = dbCmd; srcTable.Select().ToList().ForEach((r) => { r.SetAdded(); }); break; } case "UPDATE": { dbAdapter.UpdateCommand = dbCmd; srcTable.Select().ToList().ForEach((r) => { r.SetModified(); }); break; } case "DELETE": { dbAdapter.DeleteCommand = dbCmd; srcTable.Select().ToList().ForEach((r) => { r.Delete(); }); break; } default: { throw new ArgumentException("无效的SQL命令!", "sqlCmdText"); } } dbAdapter.UpdateBatchSize = batchSize; int execResult = dbAdapter.Update(srcTable); ClearCommandParameters(dbCmd); return execResult; }
插入成功的结果是:
已自己解决,原因在于参数类型,必需明确指定映射的源DATATABLE列名