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

前端 未结 3 919
夕颜
夕颜 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: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();
    }
    

提交回复
热议问题