简体   繁体   English

如何在c#Textbox中允许带有SQL空格的文本

[英]How to allow text with spaces in SQL from c# Textbox

I have this code that lets you input sentences in a textbox and it inserts in a table in SQL Server 我有这个代码,允许您在文本框中输入句子,它插入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 = "";
}

but when I press the button that calls this function, it gives out the Error 但是当我按下调用此功能的按钮时,它会发出错误

String or binary data would be truncated 字符串或二进制数据将被截断

The error indicates that the length of the string you are trying to insert in the Notes column, is longer than the maximum allowed size in that column's definition. 该错误表示您尝试在Notes列中插入的字符串的长度超过该列定义中允许的最大大小。 Try truncating the value for txtbox_Notes.Text to the specified column length. 尝试将txtbox_Notes.Text的值截断为指定的列长度。

I would also suggest you read a little bit about SQL Injection and take into account that the way you are executing this insertion command is really vulnerable to this kind of attacks. 我还建议你阅读一些关于SQL注入的内容,并考虑到你执行这个插入命令的方式真的很容易受到这种攻击。 As suggested in a comment for the question, you could also use stored procedures to execute the insertion which not only provides a (thin) layer of security but also makes your code more readable. 正如对该问题的评论中所建议的那样,您还可以使用存储过程来执行插入,这不仅提供(薄)安全层,而且还使您的代码更具可读性。

You need to use parameters in your query, otherwise you are making it very error prone and also an easy hack for SQL injection. 您需要在查询中使用参数,否则您将使其非常容易出错,并且也很容易入侵SQL。

Just try something like this and see if it work for you 试试这样的事情,看看它是否适合你

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM