Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters on SqlCommand Does not work

I am trying to run a single command to insert rows into my SQL Server 2012 database, however my parameters are not passed to the code.

con.Open();

string query = @"INSERT INTO [dbo].[Users](Username, Password, Role) 
                 VALUES (@u, @p, @r);";
var cmd = new SqlCommand(query, con);

cmd.Parameters.AddWithValue("@u", username);
cmd.Parameters.AddWithValue("@p", password);
cmd.Parameters.AddWithValue("@r", role);

cmd.ExecuteNonQuery();

con.Close();

I get SqlException with the parameterized query

'(@u nvarchar(4000),@p nvarchar(4000),@r nvarchar(1))INSERT INTO ' expects the parameter '@u', which was not supplied.

The way I see it I am passing the parameters before executing the command. Can anyone help me to find out what is missing ?

like image 676
user1470618 Avatar asked Aug 14 '26 04:08

user1470618


2 Answers

Your issue is not because of your query, it is because the variable username is NULL. When you variable username is null, it will not throw any error when you use .AddwithValue, however, it is not setting the parameter, that's why when you use that parameter, it returned you exception says the parameter is not supplied.
Use the following code, you can reproduce your issue and verify the reason. If you give username =string.Empty, it will not give you this issue.


string connStr = "Data Source=localhost;Initial Catalog=Adventure;Integrated Security=SSPI";
            SqlConnection con = new SqlConnection(connStr);
            string username = null;
            string password = string.Empty;
            string role = string.Empty;
            try
            {
                con.Open();
                string query = @"INSERT INTO [dbo].[Users]" + @"(Username ,Password , Role) " + @"VALUES (@u,@p,@r);";
                var cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@u", username);
                cmd.Parameters.AddWithValue("@p", password);
                cmd.Parameters.AddWithValue("@r", role);
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace + ex.Message);
                con.Close();
            }
like image 126
ljh Avatar answered Aug 16 '26 08:08

ljh


Add : Cmd.CommandType = CommandType.StoredProcedure; OR, Cmd.CommandType = CommandType.Text; as per requeired

like image 37
Sanjay Chitrakar Avatar answered Aug 16 '26 06:08

Sanjay Chitrakar