插入不起作用

时间:2012-09-15 15:16:46

标签: sql parameters sqlcommand scalar

我搜索了evreywhere并尝试了所有建议,但在运行以下代码时仍然没有运气。请注意,某些代码已注释掉。那就是我尝试不同的事情。

SqlConnection connection = new SqlConnection(“Data Source = URB900-PC \ SQLEXPRESS; Initial Catalog = usersSQL; Integrated Security = True”);

        string password  = PasswordTextBox.Text;
        string email     = EmailTextBox.Text;
        string firstname = FirstNameTextBox.Text;
        string lastname  = SurnameTextBox.Text;

        //command.Parameters.AddWithValue("@UserName", username);
        //command.Parameters.AddWithValue("@Password", password);
        //command.Parameters.AddWithValue("@Email", email);
        //command.Parameters.AddWithValue("@FirstName", firstname);
        //command.Parameters.AddWithValue("@LastName", lastname);

        command.Parameters.Add("@UserName", SqlDbType.VarChar);
        command.Parameters["@UserName"].Value = username;

        command.Parameters.Add("@Password", SqlDbType.VarChar);
        command.Parameters["@Password"].Value = password;

        command.Parameters.Add("@Email", SqlDbType.VarChar);
        command.Parameters["@Email"].Value = email;

        command.Parameters.Add("@FirstName", SqlDbType.VarChar);
        command.Parameters["@FirstName"].Value = firstname;

        command.Parameters.Add("@LasttName", SqlDbType.VarChar);
        command.Parameters["@LasttName"].Value = lastname;

        SqlCommand command2 = new SqlCommand("INSERT INTO users (UserName, Password, UserEmail, FirstName, LastName)" +
        "values (@UserName, @Password, @Email, @FirstName, @LastName)", connection);

        connection.Open();
        command2.ExecuteNonQuery();
        //command2.ExecuteScalar();
        connection.Close();

当我运行时,填写文本框并按下我得到的按钮......

必须声明标量变量“@UserName”。

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

这是因为您将参数附加到command然后执行不同的command2