简体   繁体   中英

WCF service keeps returning false

So I created and invoked a WCF service in C#, but keep getting a false back, I am unsure as to why it is. It might be to do with the connection string but changing it from the current just gives me errors.

Here's my code:

 //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;
   }

As Soner pointed out, your code is susceptible to SQL Injection attacks, and this can be remedied by using parameterized queries. Also, best practice is to use a using block with the connection so it is properly closed and disposed of once the code in the using block is exited (currently you're not even closing the connection when you're done).

Also, ExecuteNonQuery is sufficient for this - it will run the command and then return the number of rows affected (which should be 1 in this case). You can check the number of rows affected and use that to determine success/failure, in addition to using a catch block in the case of an exception. Realistically I would not expect anything other than the value of 1 unless an exception was thrown while executing the command.

Finally your posted code is swallowing the exception. You should do something with the exception (log it, execute some other code, rethrow it - depending on the requirements of your app) rather than simply returning false.

Putting it all together:

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;
     }
 }

The above code wraps the call in a using statement. When the command is created, the parameters are added to the SqlCommand.Parameters collection, and then ExecuteNonQuery is returned. If the result is 1, true is returned, otherwise false is returned. If an error is encountered, false is returned but again you should do something with the exception so you can troubleshoot if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM