Alvan Rahimli
Alvan Rahimli

Reputation: 384

How to add parameters to SqlCommand?

I'm trying to add parameters to SqlCommand, but it inserts parameter names instead of parameter values.

This is the code snippet:

var QueryString1 = "Insert into UsersTable (Username, Password, IsAdmin, Email, Budget, Phone) " +
                   "values ('@Un', '@P','" + user.IsAdmin + "', '@E', '@B', '@Ph')";

using (SqlCommand command = new SqlCommand(QueryString1, con))
{
    command.Parameters.Add("@Un", SqlDbType.Text);
    command.Parameters["@Un"].Value = user.UserName;
    command.Parameters.Add("@P", SqlDbType.Text);
    command.Parameters["@P"].Value = user.Password;
    command.Parameters.Add("@E", SqlDbType.Text);
    command.Parameters["@E"].Value = user.Email;
    command.Parameters.Add("@B", SqlDbType.Text);
    command.Parameters["@B"].Value = user.Budget.Amount + "-" + user.Budget.Currency;
    command.Parameters.Add("@Ph", SqlDbType.VarChar);
    command.Parameters["@Ph"].Value = user.Phone;

    if (command.ExecuteNonQuery().Equals(0))
    {
        con.Close();
        return InternalServerError();
    }

    con.Close();

    return Ok();
}

And this is the result of SQL Server

sorry for blurred records :)

Upvotes: 1

Views: 6505

Answers (2)

gouravm
gouravm

Reputation: 321

This will give you an idea of inserting data of student name and student Id in student table

using (SqlCommand command = new SqlCommand()){
      foreach (var data in result.Values)
           {
             command.Connection = conn;
             command.CommandType = CommandType.Text;
             command.CommandText = "INSERT INTO studentTable (studentId,studentName) VALUES (@studentId,@studentName)";

            // Add with value parameterName and its value
             command.Parameters.AddWithValue("@studentId", data.studentId);
             command.Parameters.AddWithValue("@studentName", data.studentName);

             command.ExecuteNonQuery();
          }
}

Hope this helps someone.

Upvotes: 2

Menahem
Menahem

Reputation: 4144

You are wrapping the variable names with single quotes, instead of wrapping the string values

Upvotes: 8

Related Questions