繁体   English   中英

SQL Server C#无法插入数据库

[英]SQL Server C# can't insert in to the database

问题:

System.Data.dll中发生类型'System.Data.SqlClient.SqlException'的异常,但未在用户代码中处理

附加信息:
参数化查询(@name nvarchar(7), @height float, @heightscale nvarchar(5), @weigh期望参数@monthDis ,未提供)

我的代码:

public partial class Step3 : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection c;

        string str = "Data Source =(LocalDB)\\MSSQLLocalDB;";
        str += "AttachDbFilename=|DataDirectory|\\DinoData.mdf;";
        str += "Integrated Security= True";

        c = new SqlConnection(str);

        if (Page.IsValid == true)
        {
            Session["yourlocation"] = ddlcountry.SelectedItem.Text;
            Session["dayborn"] = DDLborn.SelectedItem.Text;
            Session["monthborn"] = ddlmonthborn.SelectedItem.Text;
            Session["yearborn"] = txtyar.Text;
            Session["yourEmail"] = txtemail.Text;
            Session["Gender"] = rbgendere.SelectedItem.Text;
            Session["YourName"] = txtName.Text;
            Session["YourLastName"] = txtLName.Text;

            SqlCommand NewUser = new SqlCommand("INSERT INTO [DinoTable] VALUES(@name, @height, @heightscale, @weight, @weightscale, @diet, @status, @locationDis, @dayDis, @monthDis, @yearDis, @yourlocation, @dayborn, @monthborn, @yearborn, @Gender, @yourEmail, @yoname, @lastname);", c);
            NewUser.Connection = c;

            NewUser.Parameters.AddWithValue("@name", (string) Session["Name"]);
            NewUser.Parameters.AddWithValue("@height", Convert.ToDouble(Session["Height"]));
            NewUser.Parameters.AddWithValue("@heightscale", (string)Session["HeightScale"]);
            NewUser.Parameters.AddWithValue("@weight", Convert.ToDouble(Session["Weight"]));
            NewUser.Parameters.AddWithValue("@weightscale", (string)Session["weightscale"]);
            NewUser.Parameters.AddWithValue("@diet", (string)Session["diet"]);
            NewUser.Parameters.AddWithValue("@status", (string)Session["status"]);
            NewUser.Parameters.AddWithValue("@locationDis", (string)Session["locationDis"]);
            NewUser.Parameters.AddWithValue("@dayDis", Convert.ToInt32(Session["dayDis"]));
            NewUser.Parameters.AddWithValue("@monthDis", (string)(Session["monthDis"]));
            NewUser.Parameters.AddWithValue("@yearDis", Convert.ToInt32(Session["yearDis"]));
            NewUser.Parameters.AddWithValue("@yourlocation", (string)Session["yourlocation"]);
            NewUser.Parameters.AddWithValue("@dayborn", Convert.ToInt32(Session["dayborn"]));
            NewUser.Parameters.AddWithValue("@monthborn", (string)(Session["monthborn"]));
            NewUser.Parameters.AddWithValue("@yearborn", Convert.ToInt32(Session["yearborn"]));
            NewUser.Parameters.AddWithValue("@Gender", (string)Session["Gender"]);
            NewUser.Parameters.AddWithValue("@yourEmail", (string)Session["yourEmail"]);
            NewUser.Parameters.AddWithValue("@yoname", (string)Session["YourName"]);
            NewUser.Parameters.AddWithValue("@lastname", (string)Session["YourLastName"]);
            NewUser.Parameters.AddWithValue("@MoneyinMilions", 3);

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

            Response.Redirect("finish%20new.aspx", true);
        }
    }
}

谢谢大家的帮助!

查询时,未分配的会话变量将返回null 通过AddWithValue作为参数传递时,它会生成您看到的错误。

如果不需要数据库中的值(它是可为空的列),则可以测试null并使用C#合并运算符替换为DBNull.Value

NewUser.Parameters.AddWithValue("@monthDis", Session["monthDis"] ?? DBNull.Value);

或者,如果需要该值(NOT NULL列),则应提供默认值(或引发异常):

NewUser.Parameters.AddWithValue("@monthDis", Session["monthDis"] ?? "");

我对构建SQL参数的代码部分进行了一些细微调整(包括如果Namenull则抛出异常,因为这是主键):

//exit function if any required values are not specified in the Session
if (Session["Name"] == null)
{
    throw new Exception("Name is a required but not specified");
}

using (SqlCommand newUser = new SqlCommand(queryString, c))
{
    newUser.Parameters.AddWithValue("@name", Session["Name"]);
    newUser.Parameters.AddWithValue("@height", Convert.ToDouble(Session["Height"]));
    newUser.Parameters.AddWithValue("@heightscale", Session["HeightScale"] ?? "");
    newUser.Parameters.AddWithValue("@weight", Convert.ToDouble(Session["Weight"]));
    newUser.Parameters.AddWithValue("@weightscale", Session["weightscale"] ?? "");
    newUser.Parameters.AddWithValue("@diet", Session["diet"] ?? "");
    newUser.Parameters.AddWithValue("@status", Session["status"] ?? "");
    newUser.Parameters.AddWithValue("@locationDis", Session["locationDis"] ?? "");
    newUser.Parameters.AddWithValue("@dayDis", Convert.ToInt32(Session["dayDis"]));
    newUser.Parameters.AddWithValue("@monthDis", Session["monthDis"] ?? "");
    newUser.Parameters.AddWithValue("@yearDis", Convert.ToInt32(Session["yearDis"]));
    newUser.Parameters.AddWithValue("@yourlocation", Session["yourlocation"] ?? "");
    newUser.Parameters.AddWithValue("@dayborn", Convert.ToInt32(Session["dayborn"]));
    newUser.Parameters.AddWithValue("@monthborn", Session["monthborn"] ?? "");
    newUser.Parameters.AddWithValue("@yearborn", Convert.ToInt32(Session["yearborn"]));
    newUser.Parameters.AddWithValue("@Gender", Session["Gender"] ?? "");
    newUser.Parameters.AddWithValue("@yourEmail", Session["yourEmail"] ?? "");
    newUser.Parameters.AddWithValue("@yoname", Session["YourName"] ?? "");
    newUser.Parameters.AddWithValue("@lastname", Session["YourLastName"] ?? "");
    newUser.Parameters.AddWithValue("@MoneyinMilions", 3);

    c.Open();
    newUser.ExecuteNonQuery(); //if you are not returning a result set, this is what you use.  Use ExecuteQuery() if you want to return data from the DB.
    c.Close();
}

此外,插入时,必须在查询字符串中将表中所有未在数据库中配置默认​​值的必填字段指定为参数。 在插入过程中显式列出列名也是一个好习惯:

string queryString =
        "INSERT INTO [DinoTable] (DinoName, DinoHeight, Heightskale, DinoWeight, Weightskale, diet, Status, LocationDiscovery, DayDiscovery, monthDiscovery, yearDiscovery, YourLocation, DayBorn, monthBorn, YearBorn, YourGender, YourEmail, YourName, YourLastName, MoneyinMilions) VALUES(@name, @height, @heightscale, @weight, @weightscale, @diet, @status, @locationDis, @dayDis, @monthDis, @yearDis, @yourlocation, @dayborn, @monthborn, @yearborn, @Gender, @yourEmail, @yoname, @lastname, @MoneyinMilions);";

您在SQL查询中缺少@MoneyinMillions。

 SqlCommand NewUser = new SqlCommand("INSERT INTO [DinoTable] VALUES(@name, 
 @height, @heightscale, @weight, @weightscale, @diet, @status, @locationDis, 
 @dayDis, @monthDis, @yearDis, @yourlocation, @dayborn, @monthborn, @yearborn, 
 @Gender, @yourEmail, @yoname, @lastname, @MoneyinMillions);", c);

我很确定您的问题就是您的查询。

 SqlCommand NewUser = new SqlCommand("INSERT INTO [DinoTable] VALUES(@name, @height, @heightscale, @weight, @weightscale, @diet, @status, @locationDis, @dayDis, @monthDis, @yearDis, @yourlocation, @dayborn, @monthborn, @yearborn, @Gender, @yourEmail, @yoname, @lastname);", c);

您正在向查询中添加参数,但该参数很可能为null。 NewUser.Parameters.AddWithValue("@monthDis", (string)(Session["monthDis"]));

您需要按照@DevTony的建议在传递会话变量之前检查会话变量是否为null。

 protected void Button1_Click(object sender, EventArgs e)
    {
        //when using sql connection objects, be sure to enclose them in a using block to properly dispose of resources.
        string connectionString =
            @"Data Source =(LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\DinoData.mdf;Integrated Security= True;";
        //if you want to use SQL Server security, set Integrated Security to FALSE.  TRUE means use Windows Integrated Security.
        string queryString =
            "INSERT INTO [DinoTable] VALUES(@name, @height, @heightscale, @weight, @weightscale, @diet, @status, @locationDis, @dayDis, @monthDis, @yearDis, @yourlocation, @dayborn, @monthborn, @yearborn, @Gender, @yourEmail, @yoname, @lastname, @MoneyinMilions);";

        //normally, you'd print an error on the form to tell the user why their data was wrong.
        if (Session["yourLocation"] != null)
            Session["yourlocation"] = ddlcountry.SelectedItem.Text;
        else
        {
            return;
        }
        if (Session["dayborn"] != null)
            Session["dayborn"] = ddlBorn.SelectedItem.Text;
        else
        {
            return;
        }
        if (Session["monthborn"] != null)
            Session["monthborn"] = ddlmonthborn.SelectedItem.Text;
        else
        {
            return;
        }
        if (Session["yearborn"] != null)
            Session["yearborn"] = txtyar.Text;
        else
        {
            return;
        }
        if (Session["yourEmail"] != null)
            Session["yourEmail"] = txtemail.Text;
        else
        {
            return;
        }
        if (Session["Gender"] != null)
            Session["Gender"] = rbGender.SelectedItem.Text;
        else
        {
            return;
        }
        if (Session["YourName"] != null)
            Session["YourName"] = txtName.Text;
        else
        {
            return;
        }
        if (Session["YourLastName"] != null)
            Session["YourLastName"] = txtLName.Text;
        else
        {
            return;
        }


        if (Page.IsValid == true)
        {
            using (SqlConnection c = new SqlConnection(connectionString))
            {
                //not sure why you are just using session objects.  If you've disabled session for the controls,
                //then it makes sense.  Otherwise just use the dropdown's text value directly.                    

                using (SqlCommand newUser = new SqlCommand(queryString, c))
                {
                    newUser.Parameters.AddWithValue("@name", (string)Session["Name"]);
                    newUser.Parameters.AddWithValue("@height", Convert.ToDouble(Session["Height"]));
                    newUser.Parameters.AddWithValue("@heightscale", (string)Session["HeightScale"]);
                    newUser.Parameters.AddWithValue("@weight", Convert.ToDouble(Session["Weight"]));
                    newUser.Parameters.AddWithValue("@weightscale", (string)Session["weightscale"]);
                    newUser.Parameters.AddWithValue("@diet", (string)Session["diet"]);
                    newUser.Parameters.AddWithValue("@status", (string)Session["status"]);
                    newUser.Parameters.AddWithValue("@locationDis", (string)Session["locationDis"]);
                    newUser.Parameters.AddWithValue("@dayDis", Convert.ToInt32(Session["dayDis"]));
                    newUser.Parameters.AddWithValue("@monthDis", (string)(Session["monthDis"]));
                    newUser.Parameters.AddWithValue("@yearDis", Convert.ToInt32(Session["yearDis"]));
                    newUser.Parameters.AddWithValue("@yourlocation", (string)Session["yourlocation"]);
                    newUser.Parameters.AddWithValue("@dayborn", Convert.ToInt32(Session["dayborn"]));
                    newUser.Parameters.AddWithValue("@monthborn", (string)(Session["monthborn"]));
                    newUser.Parameters.AddWithValue("@yearborn", Convert.ToInt32(Session["yearborn"]));
                    newUser.Parameters.AddWithValue("@Gender", (string)Session["Gender"]);
                    newUser.Parameters.AddWithValue("@yourEmail", (string)Session["yourEmail"]);
                    newUser.Parameters.AddWithValue("@yoname", (string)Session["YourName"]);
                    newUser.Parameters.AddWithValue("@lastname", (string)Session["YourLastName"]);
                    newUser.Parameters.AddWithValue("@MoneyinMilions", 3);

                    c.Open();
                    newUser.ExecuteNonQuery(); //if you are not returning a result set, this is what you use.  Use ExecuteQuery() if you want to return data from the DB.
                    c.Close();
                }
            }
            Response.Redirect("finish%20new.aspx", true);
        }
    }

这是学习如何使用SQL连接的资源。

http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM