【问题标题】:Error:System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to numeric错误:System.Data.SqlClient.SqlException (0x80131904):将数据类型 nvarchar 转换为数值时出错
【发布时间】:2015-01-06 18:00:20
【问题描述】:

我正在尝试创建一个注册页面,但是遇到了一个额外的错误! 我想要实现的是将用户输入的代码传输到数据库中。 但是,由于单击提交按钮后遇到错误,我无法实现我想要的目标。 任何帮助将不胜感激!

Error Message:
Error:System.Data.SqlClient.SqlException (0x80131904): Error converting data type nvarchar to     numeric. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Registration.submitButton_Click(Object sender, EventArgs e) in d:\Desktop\TemporarySter\Registration.aspx.cs:line 80 ClientConnectionId:c3fd51e0-9dc7-49ba-ab88-313267504802

我的 SQL 数据库代码

  CREATE TABLE [dbo].[Client] (
    [ClientNo]     INT            IDENTITY (1, 1) NOT NULL,
    [cFirstName]   NCHAR (10)     NOT NULL,
    [cLastName]    NCHAR (50)     NOT NULL,
    [cD.O.B]       DATE           NOT NULL,
    [cCompanyName] NVARCHAR (255) NOT NULL,
    [cAddress]     NVARCHAR (255) NOT NULL,
    [cCity]        NVARCHAR (255) NOT NULL,
    [cZipCode]     NCHAR (10)     NOT NULL,
    [cPhoneNo] NUMERIC (18)   NOT NULL,
    [cFax]         NUMERIC (18)   NOT NULL,
    [cEmail]       NVARCHAR (MAX) NOT NULL,
    [cUsername]    NVARCHAR (50)  NOT NULL,
    [cPassword]    NVARCHAR (50)  NOT NULL,
    CONSTRAINT [PK_Client] PRIMARY KEY CLUSTERED ([ClientNo] ASC)
);

我的注册页面的aspx.cs代码

  using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Registration : System.Web.UI.Page
{
    static readonly string scriptErrorUsername =
        "<script language =\"javascript\">\n" +
        "alert (\"Error - Username is already taken! Please key in another Username\");\n" +
        "</script>";
    static readonly string scriptSuccessNewAccount =
        "<script language=\"javascript\">\n" +
        "alert (\"Your account has been successfully created - Thank You!\");\n" +
        "</script>";
    protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true");
            conn.Open();
            string checkuser = "select count(*) from Client where cUserName= '" + userTB.Text + "'";
            SqlCommand com = new SqlCommand(checkuser, conn);
            int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
            if (temp == 1)
            {
                Response.Write("Username is already taken! Please choose another username.");
            }
            conn.Close();
        }
    }
    protected void submitButton_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true");
            conn.Open();
            Type csType = this.GetType();
            SqlCommand com;
            SqlDataReader rdr;
            string strSQLSelect = "SELECT cUsername FROM Client ORDER BY cUsername";         
            com = new SqlCommand(strSQLSelect, conn);
            rdr = com.ExecuteReader();

            while (rdr.Read() == true)
            {
                if (userTB.Text == (string)rdr["cUsername"])
                {
                    ClientScript.RegisterStartupScript(csType, "Error", scriptErrorUsername);
                    conn.Close();
                    rdr.Close();
                    return;
                }
            }


            string insertQuery = "insert into Client (cFirstName, cLastName, [cD.O.B], cCompanyName, cAddress, cCity, cZipCode, cPhoneNo, cFax, cEmail, cUsername, cPassword) values (@firstname,@lastname,@dob,@companyname,@address,@city,@zipcode,@phoneno,@fax,@email,@username,@password)";
            com = new SqlCommand(insertQuery, conn);
            com.Parameters.AddWithValue("@firstname", firstnameTB.Text);
            com.Parameters.AddWithValue("@lastname", lastnameTB.Text);
            com.Parameters.AddWithValue("@dob", dateTB.Text.ToString());
            com.Parameters.AddWithValue("@companyname", companyTB.Text);
            com.Parameters.AddWithValue("@address", addressTB.Text);
            com.Parameters.AddWithValue("@city", cityTB.Text);
            com.Parameters.AddWithValue("@zipcode", postalcodeTB.Text);
            com.Parameters.AddWithValue("@phoneno", contactnumberTB.Text.ToString());
            com.Parameters.AddWithValue("@fax", faxTB.Text.ToString());
            com.Parameters.AddWithValue("@email", emailTB.Text);
            com.Parameters.AddWithValue("@username", userTB.Text);
            com.Parameters.AddWithValue("@password", passTB.Text);

            com.ExecuteNonQuery();
            Response.Redirect("ClientLogin.aspx");
            Response.Write("Congratulations! Your registration is successful!");
            ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);
            conn.Close();


        }
        catch (Exception ex)
        {
            Response.Write("Error:" + ex.ToString());
        }


}
    protected void resetButton_Click(object sender, EventArgs e)
    {


        Response.Redirect("~/Registration.aspx", true);

    }

} 

【问题讨论】:

  • PhoneNumbers 是字符串而不是数字。将您的数据库列(也包括传真)更改为 nvarchar。 (大小 20 应该足以容纳国际前缀、区号以及您的用户在此处输入的任何内容)。不要按照建议将您的输入转换为数字。错了……
  • 我知道我有点晚了,但是为了后代... 无关提示:SqlConnectionSqlCommandSqlDataReader 都是 IDisposable 并且应该每个都在 using块。

标签: c# asp.net registration


【解决方案1】:

您将电话号码声明为数字字段,因此您需要将文本转换为整数

 [cPhoneNo] NUMERIC (18)   NOT NULL
 [cFax]     NUMERIC (18)   NOT NULL

这样使用:

com.Parameters.AddWithValue("@phoneno", Convert.ToInt32(contactnumberTB.Text));
com.Parameters.AddWithValue("@fax", Convert.ToInt32(faxTB.Text));

STOP USING ADD WITH VALUES

【讨论】:

  • 您好,先生,又遇到了一个错误。错误:System.OverflowException:对于 Int16,值太大或太小。在 System.Int16.Parse(String s, NumberStyles style, NumberFormatInfo info) 在 System.Convert.ToInt16(String value) 在 Registration.submitButton_Click(Object sender, EventArgs e) 在 d:\Desktop\TemporarySter\Registration.aspx.cs :第 74 行
  • @SarahCollins 你放入 TextBox 的 cPhoneNo 的价值是什么
  • 我设置了一个限制,只允许 8 个数字。示例:88888888
  • @SarahCollins 我更新了。您需要使用Convert.ToInt32,因为请参阅此stackoverflow.com/questions/21161155/…
  • 虽然您的回答在技术上是正确的,但在逻辑上是错误的。电话号码不是数字而是字符串。 OP 应该更改数据列类型而不是将输入转换为数字。将 ToString 添加到 Text(字符串)属性有什么意义?
【解决方案2】:

在您的代码中进行以下更改

com.Parameters.AddWithValue("@phoneno", Convert.ToDouble(contactnumberTB.Text.ToString()));
com.Parameters.AddWithValue("@@fax", Convert.ToDouble(faxTB..Text.ToString()));

您需要进行更改,因为您尝试在数字字段中插入字符串值。 通过定义这个,您在 db 中声明以下字段是数字的,因此应用程序将失败并显示字符串值。这就是为什么需要进行上述更改才能使数值翻倍的原因。

[cPhoneNo] NUMERIC (18)   NOT NULL,
[cFax]         NUMERIC (18)   NOT NULL,

【讨论】:

    【解决方案3】:

    电话号码值是你的cs中的一个字符串:

    com.Parameters.AddWithValue("@phoneno", contactnumberTB.Text.ToString());
    

    在你的表格中是数字:

    [cPhoneNo] NUMERIC (18)   NOT NULL,
    

    [编辑:] 您应该更新表中的数据类型。

    【讨论】:

    • 虽然您的答案在技术上是正确的,但在逻辑上是错误的。电话号码不是数字而是字符串。 OP 应该更改数据列类型而不是将输入转换为数字。将字符串转换为字符串有什么意义(Text.ToString()???)
    猜你喜欢
    • 2015-06-06
    • 2012-10-14
    • 2020-03-14
    • 2023-03-16
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2015-12-24
    相关资源
    最近更新 更多