gpt4 book ai didi

c# - SQL DataAdapter.Update 中的逐行更新

转载 作者:太空宇宙 更新时间:2023-11-03 16:19:43 25 4
gpt4 key购买 nike

我在使用 DataAdapter.Update 时遇到了问题。

场景是这样的:我有一个这样的数据库表

Student
(StudentID INT NOT NULL,
STUDENTNAME NVARCHAR(100),
STUDENTIdentity INT DEFAULT 10)

在我的 Datatable 中有如下行

dsStudent

StudentID   STUDENTNAME STUDENTIdentity 
1 AAA
2 BBB 20
3 CCC

当我尝试像这样更新学生 Datatable

ds.Update(dsStudent,"Student");

这工作正常。但是我在数据库中的 studentidentity 列插入了 NULL 值而不是默认值 10。

我想实现 OnRowUpdating 事件并更改参数以实现逐行更新语句更改。

但问题是这已经在我的项目中实现了。那么我们有没有通用的解决方案来做到这一点?

我正在尝试更新的示例代码

        dr = ds.Tables["Student"].NewRow();

dr["StudentId"] = 534;

dr["StudentName"] = "robin";

ds.Tables["Student"].Rows.Add(dr);

cmdBuilder = new SqlCommandBuilder(da);

da.Update(ds, "Student");

最佳答案

不要使用 sqlcommandbuilder 生成更新命令,而是使用您自己的 sql 命令。

更新:

 SqlCommand upCmd = new SqlCommand(
"update emp set Name=@Name, Age=@Age where No=@No",con);
upCmd.Parameters.Add("@Name", SqlDbType.NChar, 10, "Name");
upCmd.Parameters.Add("@Age", SqlDbType.Int, 4, "Age");
upCmd.Parameters.Add("@No", SqlDbType.Int, 4, "No");
sqlDa.UpdateCommand = upCmd;
sqlDa.Update(dSet,"emp");

对于插入:

 SqlCommand insCmd = new SqlCommand(
"insert into emp (Name, Age) values(@Name, @Age)",con);
insCmd.Parameters.Add("@Name", SqlDbType.NChar, 10, "Name");
insCmd.Parameters.Add("@Age", SqlDbType.Int, 4, "Age");
sqlDa.InsertCommand = insCmd;
sqlDa.Update(dSet,"emp");

在参数值中提供新的行值。

试试这个让我知道/

关于c# - SQL DataAdapter.Update 中的逐行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14465928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com