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

本文关键字:许带 空格 文本 SQL c#Textbox | 更新日期: 2023-09-27 18:19:33

我有这样的代码,可以在文本框中输入句子,并插入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 = "";
}

但当我按下调用该功能的按钮时,它会显示错误

字符串或二进制数据将被截断

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

此错误表示您试图插入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 = "";
    }