简体   繁体   中英

ExecuteNonQuery C# & SQL Server

Here is my error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: The parameterized query '(@username nvarchar(3),@password nvarchar

This is my table:

CREATE TABLE [dbo].[User] 
(
    [Username]  VARCHAR (250) NOT NULL,
    [Pasword]   VARCHAR (MAX) NOT NULL,
    [FName]     VARCHAR (MAX) NOT NULL,
    [LName]     VARCHAR (MAX) NOT NULL,
    [Location]  VARCHAR (MAX) NOT NULL,
    [Profesion] VARCHAR (MAX) NOT NULL,
    [email]     VARCHAR (MAX) NOT NULL,
    [gender]    VARCHAR (MAX) NOT NULL,
    [money]     INT           NOT NULL,
    [property]  VARCHAR (MAX) NULL,

    PRIMARY KEY CLUSTERED ([Username] ASC)
);

And this is the C# code:

if (Page.IsValid)
{
    SqlCommand NewUser = new SqlCommand("INSERT INTO [User] Values (@username,@password,@name,@lastname,@location,@profesion,@email,@gender,@money,@pro);", c);
    NewUser.Connection = c;

    NewUser.Parameters.AddWithValue("@username", txtuser.Text);
    NewUser.Parameters.AddWithValue("@password", txtpass.Text);
    NewUser.Parameters.AddWithValue("@name", txtFName.Text);
    NewUser.Parameters.AddWithValue("@lastname", txtLName.Text);
    NewUser.Parameters.AddWithValue("@location", ddlcountry.SelectedItem.Text);
    NewUser.Parameters.AddWithValue("@profesion", txtprofession.Text);
    NewUser.Parameters.AddWithValue("@email", txtemail.Text);
    NewUser.Parameters.AddWithValue("@gender", rbgendere.SelectedItem.Text);
    NewUser.Parameters.AddWithValue("@money", 0);
    NewUser.Parameters.AddWithValue("@pro", null);

    Session["CurentUserid"] = txtuser.Text;

    c.Open();
    NewUser.ExecuteNonQuery();
    c.Close();

    Session["Conect"] = (bool)true;
    Response.Redirect("Finish Had Member.aspx", true);
}

Please help

I suspect the problem is that you're specifying null as the value for @pro . From the docs for AddWithValue :

Use DBNull.Value instead of null , to indicate a null value.

However, I would also suggest avoiding using AddWithValue to start with - call Add and specify the parameter type, then set the Value property. For example:

NewUser.Parameters.Add("@money", SqlDbType.Int).Value = 0;

See this blog post for detailed reasoning behind doing this.

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