如何在C#中编写UPDATE SQL查询

时间:2018-01-31 15:10:26

标签: c# sql

以下查询引发异常,我不知道原因:

  

消息:测试方法MainTest.MySkillDevelopmentTests.SupervisorFieldAndNamePresent引发异常:   System.Data.SqlClient.SqlException:'where UserName ='附近的语法不正确。   字符串''后面的未闭合引号。

代码:

public static List<List<string>> SetMyGpidAsSupervisorGPID(string gpid)
{
     string query = string.Format("UPDATE [" + dbName + "].[dbo].[MasterDatas] "
                                + "SET SupervisorGPID = " + gpid + "'"
                                + " WHERE UserName = strenev");
    return ConnectToDB(query);
}

3 个答案:

答案 0 :(得分:2)

在这种情况下,不要使用string.Format(),当你已经拥有的是字符串时。

您的查询缺少2个位置的封闭单引号。使用以下代码:

string query = "UPDATE [" + dbName + "].[dbo].[MasterDatas] "
                                + "SET SupervisorGPID = '" // here ' is missing
                                + gpid + "'"
                                + " WHERE UserName = 'strenev'"; // here surrounding '' is missing

顺便说一句,您需要更多地了解SQL-Injection等,以了解这不是一个好的/安全的做法。

根据评论进行编辑(感谢您的建议):

没有SQL注入的代码(参考:What are good ways to prevent SQL injection?):

string query = "UPDATE [dbname].[dbo].[MasterDatas] "
  //// assuming dbName is not a variable which a user-decides as it generally can't be, and rather a fixed string.
                + "SET SupervisorGPID = @gpid"+
               + " WHERE UserName = 'strenev'"; // here surrounding '' is missing
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(query, connection);
    command.Parameters.Add("@dbName", SqlDbType.NVarchar);
    command.Parameters["@dbName"].Value = dbName;
    command.Parameters.Add("@gpID", SqlDbType.Int);
    command.Parameters["@gpID"].Value = gpid;

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch (Exception ex)
    {
        //catch and handle OR throw;
    }
}

答案 1 :(得分:0)

字符串常量必须用单引号括起来。

where UserName='strenev';      // surround with quotes.

答案 2 :(得分:0)

例如,在您的情况下使用参数化查询 UserName = @name并使用sqlcommand,您可以在其中引用sql参数@name和值&#39; strenev&#39;在里面。参考 Why do we always prefer using parameters in SQL statements?

"UPDATE [" + dbName + "].[dbo].[MasterDatas] "
                                    + "SET SupervisorGPID = " + gpid 
                                    + " WHERE UserName = 'strenev'");