[英]How to allow text with spaces in SQL from c# Textbox
我有这个代码,允许您在文本框中输入句子,它插入SQL Server中的表
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
con.Open();
SqlCommand com = new SqlCommand("Insert Into tbl_notes (Notes,date_time) Values('" + txtbox_Notes.Text + "','" + DateTime.Now + "')", con);
com.ExecuteNonQuery();
txtbox_Notes.Text = "";
}
但是当我按下调用此功能的按钮时,它会发出错误
字符串或二进制数据将被截断
该错误表示您尝试在Notes
列中插入的字符串的长度超过该列定义中允许的最大大小。 尝试将txtbox_Notes.Text
的值截断为指定的列长度。
我还建议你阅读一些关于SQL注入的内容,并考虑到你执行这个插入命令的方式真的很容易受到这种攻击。 正如对该问题的评论中所建议的那样,您还可以使用存储过程来执行插入,这不仅提供(薄)安全层,而且还使您的代码更具可读性。
您需要在查询中使用参数,否则您将使其非常容易出错,并且也很容易入侵SQL。
试试这样的事情,看看它是否适合你
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
con.Open();
SqlCommand com = new SqlCommand("Insert Into tbl_notes (Notes,date_time) Values(@Notes,@DateTime)", con);
com.Parameters.Add(new SqlParameter("@Notes", txtbox_Notes.Text));
com.Parameters.Add(new SqlParameter("@DateTime", DateTime.Now));
com.ExecuteNonQuery();
txtbox_Notes.Text = "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.