Database insert error: “string or binary data would be truncated”

前端 未结 3 920
夕颜
夕颜 2021-01-11 11:23

When I log in, I am storing my username in the session. My requirement is that I want to store my username in my database. Here I am storing it in username1. Wh

相关标签:
3条回答
  • 2021-01-11 11:29

    This error mostly happen when the inserting value is larger than the field width defined in table on SQL Server.

    Check if you are inserting date and time using DateTime.Now c# fuction, your Table must be of type DateTime. not Date or Time only.

    0 讨论(0)
  • 2021-01-11 11:45

    I would recommend you using a parametrized query. Your code is now vulnerable to SQL injection. Also you should use the ExecuteNonQuery method on the SQL command instead of ExecuteScalar when inserting values to the database:

    var connectionString = "Data Source=.;database=testdb1;Integrated Security=SSPI";
    using (SqlConnection con = new SqlConnection(connectionString))
    using (SqlCommand cmd = con.CreateCommand())
    {
        con.Open();
        cmd.CommandText = "INSERT INTO qry_details VALUES (@query_name, 'pending for approval', @query_description, @date, @qry, @username)";
        cmd.Parameters.AddWithValue("@query_name", txt_query_name.Text);
        cmd.Parameters.AddWithValue("@query_description", txt_query_description.Text);
        cmd.Parameters.AddWithValue("@date", DateTime.Now);
        cmd.Parameters.AddWithValue("@qry", qry);
        cmd.Parameters.AddWithValue("@username", uname1);
        cmd.ExecuteNonQuery();
    }
    
    0 讨论(0)
  • 2021-01-11 11:47

    check the length of qry_details table and see if its smaller than the string you send to the db?

    basically the exception says you are trying to something bigger than the column length.

    0 讨论(0)
提交回复
热议问题