C# SQLDataAdapter - Issues with INSERT

本文关键字:with INSERT Issues SQLDataAdapter | 更新日期: 2023-09-27 18:11:02

请参考我开始这一切的问题:c# SQLDataAdapter - Not insert data into DB

我正在开发一个档案系统,嗯,我应该说建立在它的基础上。但是我最近的问题是这样的,一旦我点击var rowsAffected = sqlAdapter.InsertCommand.ExecuteNonQuery();:

Additional information: The parameterized query '(@TableID int,@RowID int,@RowState tinyint,@UserID int,@XMLHisto' expects the parameter '@TableID', which was not supplied.

现在它可能变得有点棘手…我试图插入的表,它们没有关联的主键或外键。这不是我的设计。我想知道上面的execute()调用是否因此在INSERT中遇到了麻烦。我没有任何东西我需要设置为@@身份,因为…嗯,我没有那样的东西可用。

想法吗?

:

按要求,这里是查询和sql cmd..

string strInsertSQL = "INSERT INTO <tableName> (TableID, RowID, ModifyDate, RowState, UserID, XMLHistory, RowDescription) " +
                            "VALUES (@TableID, @RowID, GetDate(), @RowState, @UserID, @XMLHistory, @RowDescription); SET @NewID = @@Identity"; // SET statement needed? 
sqlComm = new SqlCommand(strInsertSQL, sqlConnArchive);
sqlComm.Parameters.Add("@TableID", SqlDbType.Int, 4, "TableID"); // Not sure if this is needed since primary key doesn't exist? 
// More params added here

更新:

心血来潮,我想检查一下InsertCommand。参数。我看了看@TableID value,它是Null。

sqlAdapter.Fill(myDS.myTable); // myTable.count = 7k+
var x = sqlAdapter.InsertCommand.Parameters; // x-@tableID value = null
var rowsAffected = sqlAdapter.InsertCommand.ExecuteNonQuery();

我有一种感觉,这就是为什么我看到这个错误。有人对我如何解决这个问题有什么想法吗?

C# SQLDataAdapter - Issues with INSERT

错误是因为它是空的。

将TableID列作为表中的Identity。

我不知道你实际上在哪里设置参数的值。您添加了参数,但是您的代码没有显示您曾经用一个值填充参数。

sqlComm = new SqlCommand(strInsertSQL, sqlConnArchive);
var tableIdParam = new SqlParameter("@TableId", SqlDbType.Int, 4);
tableIdParam.Value = 99; //whatever id value you want to set here
sqlComm.Parameters.Add(tableIdParam);

另一方面,如果TableId列有标识规范,则修改sql字符串并将TableId完全排除-数据库将在插入时提供它

当然你不提供值…

方法

sqlComm.Parameters.Add("@TableID", SqlDbType.Int, 4, "TableID")
// the value '4' here specifies the size of the column not value.
// for example max length of a string if you are about to supply a varchar

.

可以通过两种方法提供一个值

sqlComm.Parameters.Add("@TableID", SqlDbType.Int).Value = 4;

sqlComm.Parameters.AddWithValue("@TableID", 4);

您正在创建数据适配器,但是您使用数据适配器的方式就像使用SqlCommand。

关于使用数据适配器的方法,请参考以下内容:Using data adapter

使用sql命令,

string strInsertSQL = "INSERT INTO <tableName> (TableID, RowID, ModifyDate, RowState, UserID, XMLHistory, RowDescription) " +
                            "VALUES (@TableID, @RowID, GetDate(), @RowState, @UserID, @XMLHistory, @RowDescription)"
sqlComm = new SqlCommand(strInsertSQL, sqlConnArchive);
sqlComm.Parameters.Add("@TableID", SqlDbType.Int).Value = 1; //Set it to the value you want to insert
..... the rest of the parameters
sqlConnArchive.Open();
sqlComm.ExecuteNonQuery();