【问题标题】:ASP.NET - VB.NET - SQL Server Express 2012 - Storing datesASP.NET - VB.NET - SQL Server Express 2012 - 存储日期
【发布时间】:2013-03-17 22:22:07
【问题描述】:

我正在尝试从日历控件中获取所选日期并将其存储到数据库中的列中。

我收到以下错误:

SqlDateTime 溢出。必须在 1753 年 1 月 1 日凌晨 12:00:00 到 9999 年 12 月 31 日晚上 11:59:59 之间。

出生日期数据库栏:

VB.注册页面代码:

        Public Sub register()



        Dim Username As String = txtUsername.ToString
        Dim Surname As String = txtSurname.ToString
        Dim Password As String = txtPassword.ToString
        Dim Name As String = txtName.ToString
        Dim Address1 As String = txtAddress1.ToString
        Dim Address2 As String = txtAddress2.ToString
        Dim City As String = txtCity.ToString
        Dim Email As String = txtEmail.ToString
        Dim Country As String = drpCountry.ToString
        Dim DOB As Date = calDOB.SelectedDate.Date
        Dim Occupation As String = txtOccupation.ToString
        Dim WorkLocation As String = txtWorkLocation.ToString
        Dim Age As Integer = "20"

        lblDOB.Text = DOB.ToString
        lblDOB.Visible = True


        Dim ProjectManager As String = "test"
        Dim TeamLeader As String = "test"
        Dim TeamLeaderID As Integer = "1"
        Dim ProjectManagerID As Integer = "1"

        Dim RegistrationDate As Date = DateTime.Today
        Dim ContractType As String = "test"
        Dim ContractDuration As Integer = 6
        Dim Department As String = "test"

        Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
        Dim registerSQL As SqlCommand
        Dim sqlComm As String

        sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
            "City, Country, date_of_birth, age, Occupation, department, work_location, " +
            "project_manager,team_leader, team_leader_id, project_manager_id, " +
            "date_registration, contract_type, contract_duration) " +
            "VALUES(@p1, @p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11,@p12,@p13,@p14,@p15," +
            "@p16,@p17,@p18,@p19,@p20)"

        conn.Open()
        registerSQL = New SqlCommand(sqlComm, conn)
        registerSQL.Parameters.AddWithValue("@p1", Username)
        registerSQL.Parameters.AddWithValue("@p2", Password)
        registerSQL.Parameters.AddWithValue("@p3", Name)
        registerSQL.Parameters.AddWithValue("@p4", Surname)
        registerSQL.Parameters.AddWithValue("@p5", Address1)
        registerSQL.Parameters.AddWithValue("@p6", Address2)
        registerSQL.Parameters.AddWithValue("@p7", City)
        registerSQL.Parameters.AddWithValue("@p8", Country)
        registerSQL.Parameters.AddWithValue("@p9", DOB)
        registerSQL.Parameters.AddWithValue("@p10", Age)
        registerSQL.Parameters.AddWithValue("@p11", Occupation)
        registerSQL.Parameters.AddWithValue("@p12", Department)
        registerSQL.Parameters.AddWithValue("@p13", WorkLocation)
        registerSQL.Parameters.AddWithValue("@p14", ProjectManager)
        registerSQL.Parameters.AddWithValue("@p15", TeamLeader)
        registerSQL.Parameters.AddWithValue("@p16", TeamLeaderID)
        registerSQL.Parameters.AddWithValue("@p17", ProjectManagerID)
        registerSQL.Parameters.AddWithValue("@p18", RegistrationDate)
        registerSQL.Parameters.AddWithValue("@p19", ContractType)
        registerSQL.Parameters.AddWithValue("@p20", ContractDuration)




        registerSQL.ExecuteNonQuery()


    End Sub



End Class

异常跟踪:

System.Data.SqlClient.SqlException was unhandled by user code
  Class=16
  ErrorCode=-2146232060
  HResult=-2146232060
  LineNumber=1
  Message=String or binary data would be truncated.
The statement has been terminated.
  Number=8152
  Procedure=""
  Server=BRIAN-PC\SQLEXPRESS
  Source=.Net SqlClient Data Provider
  State=13
  StackTrace:
       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)
       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.register() in C:\Users\Brian\Google Drive\Dropbox\Dropbox\THESIS\ThesisApp\Registration.aspx.vb:line 89
       at Registration.btnRegister_Click(Object sender, EventArgs e) in C:\Users\Brian\Google Drive\Dropbox\Dropbox\THESIS\ThesisApp\Registration.aspx.vb:line 14
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

更新:添加了新的错误消息,因为我修复了 RegistrationDateDOB。现在我收到一条新的错误消息:

String or binary data would be truncated.
The statement has been terminated. 

感谢任何帮助!

【问题讨论】:

  • @marc_s 我仍然遇到同样的错误!
  • 当您将DOB 分配给parameteR 时,它有什么?另外:这里还涉及DATETIME 类型的其他列吗?表上是否有一个触发器可以将一个新的插入到具有DATETIME 列的审计表中?
  • @marc_s Dim RegistrationDate As Date = 今天,但它在 DOB 上停止
  • @Brian 您的字段长度为 20 个字符宽,即 nchar(20) .. 您输入的字段是否大于 20 个字符?错误String or binary data would be truncated 表示插入的数据长度大于列长度。
  • 看起来您需要使用 Option Strict On (msdn.microsoft.com/en-us/library/zcd4xwzs%28v=vs.80%29.aspx),因为您正在尝试将字符串分配给整数,例如Dim Age As Integer = "20",因此该选项可能会为您突出显示其他问题。

标签: asp.net vb.net date datetime sql-server-2012-express


【解决方案1】:

这可能有点用
http://jwcooney.com/2012/09/10/asp-net-choosing-parameters-add-or-parameters-addwithvalue/

esp.第二点隐式数据转换导致数据错误

..You can accidentally introduce data errors if you use the Parameters.AddWithValue syntax to send a date datatype to your database, then you are at the mercy of the database to identify how it will store your date value. This can lead to problems since there are numerous ways of entering dates: mm/dd/yyyy in North America, dd/mm/yyyy in the UK, and yyyy-mm-dd as an upcoming standard. The database will look at the date value of 1/2/2012 that you are sending and can handle the ’1′ as either the day or as the month.

我建议使用:

registerSQL.Parameters.Add("@p9", SqlDbType.DateTime).Value = DOB.Date

而不是registerSQL.Parameters.AddWithValue("@p9", DOB)

确保DOB 不是DateTime.MinValueDateTime.MaxValue

也可以参考这个问题:

Difference between adding parameters to stored procedure in SQL Server 2005

【讨论】:

  • 我回应了这个答案 - 我在使用 AddWithValue 时遇到了这种问题。
【解决方案2】:

当您将DOB 分配给参数@p9 时,它有什么??

或者RegistrationDate 是罪魁祸首?当您将它分配给参数@p18 时,该变量有什么

如果您在 SQL Server 中有一个 DATETIME 列,并且您尝试将 .NET 应用程序中的 NULL 插入其中,则通常会发生此错误 - 将转换为值范围之外的 01/01/0001DATETIME

因此我的建议:在 SQL Server 2008 和更新版本中使用 DATE(如果您只需要日期 - 没有时间)或 DATETIME2(日期和时间)(DATETIME2 可以没有DATETIME那样有这些值范围限制)

【讨论】:

  • 所以Dim DOB As Date = calDOB.SelectedDate 然后registerSQL.Parameters.AddWithValue("@p9", DOB) 应该可以“开箱即用”?
  • @Brian:当然 - 但是 what value 在你的情况下是 calDOB.SelectedDate?这是一个真正的价值还是NULL??
  • calDOB.SelectedDate #3/15/2013# Date
  • @Brian:好吧,新的错误消息只是意味着您将至少一个字符串参数设置为比定义的更长的字符串在数据库表中;你大多有nvarchar(20) - 所以当你设置参数时确保你的字符串都不超过20个字符!
  • 我怎么知道是哪一个问题?因为几乎我所有的字段都是 nchar(20) 或 nchar(50) 并且我只在文本框中输入一个字符?
猜你喜欢
  • 2014-02-15
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多