Click here to Skip to main content
15,921,295 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Must declare the scalar variable "@Address". please solve

my code is below.

C#
namespace DLayer
{
    public class clsDlayer
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["strcon"].ConnectionString.ToString());
        public string DLSave(string emp_id,string name,string salary,string Address)
        {
            string res = "";
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into employee (emp_id,name,salary,Address) values (@emp_id, @name, @salary, @Address", con);
            cmd.Parameters.AddWithValue("@emp_id", emp_id);
            cmd.Parameters.AddWithValue("@name", name);
            cmd.Parameters.AddWithValue("@salary", salary);

            cmd.Parameters.AddWithValue("@Address", Address);
            
            cmd.ExecuteNonQuery();
            con.Close();
            res = "Data saved";
            return res;
        }

    }
}
Posted
Updated 31-Jul-13 21:34pm
v2

Hi,

You are missing last closing bracket in query.

SQL
SqlCommand cmd = new SqlCommand("insert into employee (emp_id,name,salary,Address) values (@emp_id, @name, @salary, @Address)", con);
 
Share this answer
 
v2
Look at your SQL string:
C#
SqlCommand cmd = new SqlCommand("insert into employee (emp_id,name,salary,Address) values (@emp_id, @name, @salary, @Address", con);
Now add the closing bracket:
C#
SqlCommand cmd = new SqlCommand("insert into employee (emp_id,name,salary,Address) values (@emp_id, @name, @salary, @Address)", con);
 
Share this answer
 
try like this:
C#
SqlCommand cmd = new SqlCommand("insert into employee (emp_id,name,salary,Address) values (" + emp_id.ToString() + ", '" + name + "', " + salary.ToString() + ", '" + Address + "')", con);

cmd.ExecuteNonQuery();
 
Share this answer
 
Comments
Gautam Raithatha 1-Aug-13 3:46am    
and yes, you were missing last closing bracket in query...
Have you ever heard about SQLInjection[^]?
I would suggest you to use stored procedure[^] rather than query in code.

HOW TO: Call a Parameterized Stored Procedure by Using ADO.NET and Visual C# .NET[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900