C# 如何从c文本框中允许SQL中带有空格的文本

C# 如何从c文本框中允许SQL中带有空格的文本,c#,sql-server,C#,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

我有一段代码,可以让您在文本框中输入句子,并将其插入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的值截断为指定的列长度


我还建议您阅读一下,并考虑到您执行此插入命令的方式确实容易受到此类攻击。正如问题注释中所建议的,您还可以使用存储过程来执行插入操作,这不仅提供了一层薄薄的安全性,而且使您的代码更具可读性。

错误表明您尝试在Notes列中插入的字符串的长度,大于该列定义中允许的最大大小。尝试将txtbox_Notes.Text的值截断为指定的列长度


我还建议您阅读一下,并考虑到您执行此插入命令的方式确实容易受到此类攻击。正如在问题的注释中所建议的,您还可以使用存储过程来执行插入,这不仅提供了一层薄薄的安全性,而且使您的代码更具可读性。

您需要在查询中使用参数,否则很容易出错,也很容易被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 = "";
    }

您需要在查询中使用参数,否则会使查询非常容易出错,并且很容易被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 = "";
    }

您可能应该使用参数化查询。您的SQL列未设置为接受您尝试插入的注释的长度。更改列长度或截断文本。您可能应该使用参数化查询。SQL列未设置为接受您尝试插入的注释的长度。更改列长度,或截断文本。如果我使用存储过程,它不会受到SQL注入的影响吗?肯定比字符串串联安全。如果我使用存储过程,它不会受到SQL注入的影响吗?肯定比字符串串联安全。