【问题标题】:WCF service keeps returning falseWCF 服务不断返回 false
【发布时间】:2014-10-22 07:32:26
【问题描述】:

因此,我在 C# 中创建并调用了 WCF 服务,但一直收到错误回复,我不确定为什么会这样。这可能与连接字符串有关,但从当前更改它只会给我错误。

这是我的代码:

 //Create the new connection
  SqlConnection myConnection = new SqlConnection();

 //Create the query
 String myQuery = "INSERT INTO Player  (registrationID,  firstName,  lastName,  phoneNumber,  Address,  dateOfBirth) " +
                   " VALUES ('" + registrationID + "', '" + firstName + "', '" + lastName + "', '" + phoneNumber + "', '" + Address + "', '" + dateOfBirth + "');";

  //The connectionString can be found in the properties table of the database
  myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";

  //Initialuze the command
  SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
  SqlDataReader myReader;

  //Run the command
  try 
  {
          myConnection.Open();
          myReader = myCommand.ExecuteReader();
          //Return true if it was successful
          return true;
   }
   catch (Exception ex) 
   {
          return false;
   }

【问题讨论】:

  • 您是否尝试过删除catch 块,以便服务崩溃并告诉您出了什么问题?
  • 有什么错误?您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。由于您使用的是INSERT 语句,因此没有必要使用ExecuteReader。因为您的查询不返回任何数据,它只是插入数据。只需改用ExecuteNonQuery。还可以使用using 语句来处理您的数据库连接和对象。
  • 如果你不对异常做任何事情(例如,记录它或其他什么),那么捕获异常就没有什么意义了。遇到异常时简单地返回 false 意味着您正在吞下该异常,这将使故障排除变得很痛苦。

标签: c# sql database wcf ado.net


【解决方案1】:

正如 Soner 所指出的,您的代码容易受到 SQL 注入攻击,这可以通过使用参数化查询来解决。此外,最佳做法是在连接中使用 using 块,以便在退出 using 块中的代码后正确关闭和处理它(目前您完成后甚至没有关闭连接) .

另外,ExecuteNonQuery 就足够了——它会运行命令,然后返回受影响的行数(在这种情况下应该是 1)。除了在异常情况下使用catch 块之外,您还可以检查受影响的行数并使用它来确定成功/失败。实际上,除了 1 的值之外,我不会期待任何其他值除非在执行命令时抛出异常。

最后,您发布的代码正在吞噬异常。您应该对异常做一些事情(记录它,执行一些其他代码,重新抛出它 - 取决于您的应用程序的要求),而不是简单地返回 false。

把它们放在一起:

using (SqlConnection myConnection = new SqlConnection())
{

    // Create the query
    String myQuery = "INSERT INTO Player  (registrationID,  firstName,  lastName,  phoneNumber,  Address,  dateOfBirth) " +
               " VALUES (@RegistrationID, @FirstName, @LastName, @PhoneNumber, @Address, @DateOfBirth)";

    //The connectionString can be found in the properties table of the database
    myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";

    //Initialuze the command
    SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
    myCommand.CommandType = CommandType.Text;
    // Here you add the values for the parameters in the query
    myCommand.Parameters.Add("@RegistrationID", SqlDbType.VarChar).Value = registrationID;
    myCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = firstName;
    myCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = lastName;
    myCommand.Parameters.Add("@PhoneNumber", SqlDbType.VarChar).Value = phoneNumber;
    myCommand.Parameters.Add("@Address", SqlDbType.VarChar).Value = address;
    myCommand.Parameters.Add("@DateOfBirth", SqlDbType.VarChar).Value = dateOfBirth;

    //Run the command
    try 
    {
        myConnection.Open();
        int rowsAffected = myCommand.ExecuteNonQuery();

        if (rowsAffected == 1)
        {
            return true;
        }
        else
        {
            return false;
        }

     }
     catch (Exception ex) 
     {
         // Do something with the exception, like logging it so you can review the error 
         return false;
     }
 }

上面的代码将调用包装在using 语句中。创建命令时,会将参数添加到SqlCommand.Parameters 集合中,然后返回ExecuteNonQuery。如果结果为 1,则返回 true,否则返回 false。如果遇到错误,则返回 false,但您应该再次对异常进行处理,以便在需要时进行故障排除。

【讨论】:

  • 谢谢你,这真的很有帮助!您付出的比要求的要多,希望其他人会发现这很有用!再次感谢。
  • 还有一件事,我似乎遇到了连接字符串的问题,我从属性中取出了一个,但似乎不起作用。有什么建议吗?
  • @Cornelis - 什么样的麻烦?你有例外吗?您使用的是什么数据库(MS SQL、Access、MySQL 等)?您也可以查看connectionstrings.com - 他们几乎所有内容都有连接字符串。
  • SQL,但在 Visual Studio 中使用内置。遇到异常。
  • 异常信息是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2021-02-13
相关资源
最近更新 更多