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

筅森魡賤 提交于 2019-12-10 21:35:06

问题


I'm trying to create a simple registration form, where data from textboxes etc. are input into a table called users:

user_id     int
username    nchar(20)
password    nchar(20)
... more columns

Code:

Dim Username As String = txtUsername.ToString
... more variable declarations

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

Dim ProjectManager As String = "test"
... more constant declarations

Dim conn As New SqlConnection("...conn string...")

sqlComm = "INSERT INTO users(Username, Password, ...other columns...)" +
    "VALUES(@p1, @p2, ...other params...)"

conn.Open()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("@p1", Username)
... other AddWithValues

registerSQL.ExecuteNonQuery()

I'm getting this error message:

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


回答1:


Yes, you are allowing any old string that people are typing in. You need to constrain each parameter to the maximum length allowed in that column. For example, if you don't want the error, you can truncate username to 20 characters or you can raise your own error when that parameter value is more than 20 characters. To truncate you could simply say:

Dim Username As String = txtUsername.ToString.Substring(0,20)

Or better yet, when you build your form, specify a MaxLength for the form field that matches the column in your table. Why let a user type in more than 20 characters if your table is only designed to hold 20?

As an aside, nchar is a terrible data choice for most of this data, unless usernames, passwords, etc. will always be exactly 20 characters. You should strongly consider nvarchar.




回答2:


You are inserting string data in table which has more size than the size of column where you are storing it in table.

That is, you are passing Username to database which has size more than 20 characters.




回答3:


Please change nchar(20) to varchar(50)



来源:https://stackoverflow.com/questions/15690642/error-string-or-binary-data-would-be-truncated-the-statement-has-been-terminat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!