使用ADODB.Parameters更正MS SQL Update语句语法C#?

时间:2016-09-16 21:54:40

标签: c# sql-server adodb

以下是适用于Insert的代码 - 我只需要帮助将其转换为带有values和where子句语法的Update。

 ADODB.Command cmdInsert = new ADODB.Command();
 cmdInsert.ActiveConnection = conn;

 cmdInsert.CommandText = "INSERT INTO ExchangeTypes(MarketSelectionId) VALUES (?)";

 //Update statement to be modelled:
 //cmdUpdate.CommandText = "Update ExchangeTypes SET
 //LayOdds = '" & layOdds & "'" & ", 
 //Size='" & laySize & "' WHERE
 //MarketId='" & marketid & "'" and SelectionId='" & selectionid & "'"

 cmdInsert.CommandType = ADODB.CommandTypeEnum.adCmdText;

// Append the parameters 
ADODB.Parameter paramMS = cmdInsert.CreateParameter(
           "MarketSelectionId",                         // Parameter name 
           ADODB.DataTypeEnum.adVarChar,                // Parameter type (adVarChar) 
           ADODB.ParameterDirectionEnum.adParamInput,   // Parameter direction 
           200,                                         // Max size 
           umarketiduselectionid);                      // Parameter value 

           cmdInsert.Parameters.Append(paramMS);

           object nRecordsAffected = Type.Missing;
           object oParams = Type.Missing;
           cmdInsert.Execute(out nRecordsAffected, ref oParams,
           (int)ADODB.ExecuteOptionEnum.adExecuteNoRecords);

2 个答案:

答案 0 :(得分:1)

您可以按照以下步骤更新您的表格:

语法: MSDN

Update YourTable
Set Column = Value
Where Condition
cmdInsert.CommandText = "Update ExchangeTypes Set MarketSelectionId =  VALUE 
Where MarketSelectionId = '?' ";

答案 1 :(得分:1)

ADODB很古老而且已被弃用。它的存在仅仅是为了向后兼容旧的vb6时代代码。它应从不用于新代码。

尝试使用ADO.Net代替插入:

using (var conn As new SqlConnection("connection string here"))
using (var cmd As new SqlCommand("INSERT INTO ExchangeTypes(MarketSelectionId) VALUES (@MarketSelectionId)", conn)
{
    cmd.Parameters.Add("@MarketSelectionId", SqlDbType.VarChar, 200).Value = umarketiduselectionid;

    conn.Open();
    cmd.ExecuteNonQuery();
}

然后UPDATE查询看起来像这样:

using (var conn As new SqlConnection("connection string here"))
using (var cmd As new SqlCommand("Update ExchangeTypes SET LayOdds = @LayOdds, Size = @LaySize WHERE MarketId= @MarketId AND SelectionId = @SelectionID ", conn)
{
    //Guessing at your column types/lengths here
    cmd.Parameters.Add("@LayOdds", SqlDbType.VarChar, 200).Value = layOdds;
    cmd.Parameters.Add("@LaySize", SqlDbType.Int).Value = laySize;
    cmd.Parameters.Add("@MarketId", SqlDbType.Int).Value = marketid;
    cmd.Parameters.Add("@SelectionId", SqlDbType.Int).Value = selectionid;

    conn.Open();
    cmd.ExecuteNonQuery();
}