使用一个查询字符串更新SQL数据库中的2行" UPDATE"

时间:2015-05-07 00:54:50

标签: c# sql asp.net visual-studio-2013

我需要弄清楚如何更新数据库中的两行,但是cnt让我的查询字符串正确..

这是我正在使用的代码。如果你能为我提供一个很棒的查询字符串..

string birdnametextupdate = birdsnametext.Text;
string birdnamedetailsupdate = birdnamedetails.Text;

int row = int.Parse(Request.QueryString["PhotoID"]);

string query = "UPDATE Photos Set PhotoName = @PhotoNewName Set Deatils = @DetailsNew WHERE PhotoID = @PhotoID";

SqlCommand myCommand = new SqlCommand(query, myConnection);

//create parameterised object
myCommand.Parameters.AddWithValue("@PhotoNewName", birdnametextupdate);
myCommand.Parameters.AddWithValue("@DetailsNew", birdnamedetailsupdate);

myCommand.Parameters.AddWithValue("@PhotoID", row);

myCommand.ExecuteNonQuery();

2 个答案:

答案 0 :(得分:1)

试试这个

 string query = "UPDATE Photos Set PhotoName = '@PhotoNewName' ,Details  = '@DetailsNew' WHERE PhotoID = '@PhotoID'";

我在查询中看到错误,不重复设置。只需使用逗号

答案 1 :(得分:1)

int photoId = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos SET PhotoName = @PhotoNewName, Details = @DetailsNew WHERE PhotoID = @PhotoID";

using(var cmd = new SqlCommand(query, myConnection))
{
    cmd.Parameters.Add("@PhotoNewName").Value = birdsnametext.Text;
    cmd.Parameters.Add("@DetailsNew").Value = birdnamedetails.Text;
    cmd.Parameters.Add("@PhotoID").Value = photoId;
    cmd.ExecuteNonQuery();
}

Sql语法是: https://msdn.microsoft.com/en-us/library/ms177523.aspx

一个简单的例子是:

UPDATE <tableName>
SET
    <Column1> = <newColumn1Value>
   ,<Column2> = <newColumn2Value>
WHERE <condition>