String or binary data would be truncated exception?

我怕爱的太早我们不能终老 提交于 2019-12-07 18:52:08

问题


 cmd = new SqlCommand("INSERT INTO sms_sentmessages(Mobilefrom,Mobileto,Message,senddate) VALUES('" + str.Substring(0, str.Length - 4).ToString() + "','" + number + "','" + txtmessage.Text.Replace("'", "''").Trim() + "',getdate())", con);
                                    cmd.CommandType = CommandType.Text;
                                    cmd.ExecuteNonQuery();

回答1:


str.Substring(0, str.Length - 4)

and/ or

txtmessage.Text.Replace("'", "''").Trim()

are too large to fit with the column you're trying to insert into.




回答2:


Well, presumably you're trying to insert a value into the table and it exceeds the length for the column. You should validate the data before you try to execute the SQL insert.

However, you should also use a parameterized query - currently your code is vulnerable to a SQL injection attack. See the Bobby Tables site for more information. Basically, parameterized SQL allows you to keep the code (SQL) separate from the data (parameters), making your code clearer and preventing SQL injection attacks (assuming you're not also using dynamic SQL).

(Finally, it's not clear why you're calling ToString() on the result of a Substring call...)




回答3:


Your data (or possibly a trigger) is too big to fit into the column you are trying to store it.

At least, that's my best guess.



来源:https://stackoverflow.com/questions/5872300/string-or-binary-data-would-be-truncated-exception

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