错误:System.Data.SqlClient.SqlException (0x80131904): 将数据类型 nv

本文关键字:nv 0x80131904 数据类型 SqlException System Data SqlClient 错误 | 更新日期: 2023-09-27 18:36:23

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

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);
    }
} 

错误:System.Data.SqlClient.SqlException (0x80131904): 将数据类型 nv

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

 [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));

停止使用"与值相加"

在代码中进行以下更改

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,

电话号码值是 css 中的字符串:

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

在您的表中,它是数字:

[cPhoneNo] NUMERIC (18)   NOT NULL,

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