简体   繁体   中英

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

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. Try truncating the value for txtbox_Notes.Text to the specified column length.

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. 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.

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 = "";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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