13

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. When the username is entered, I can print it using response.write() and it is printing perfectly. However, when I am storing it in the database it is producing this error:

**sqlException was unhandled by user code
and exception at       cmd.ExecuteScalar();
String or binary data would be truncated.
The statement has been terminated.**

Following is my ado.net code:

using (SqlConnection con = 
    new SqlConnection("Data Source=.;database=testdb1;Integrated Security=SSPI")) {

    con.Open();
    //  SqlCommand cmd = new SqlCommand("delete from fileinfo where ID=" + Convert.ToInt32(Request.Params["one"]), con);                            

    string uname = (string) Session["fname"].ToString() + " " + Session["lname"].ToString(); //Session["fname"].ToString()+" "+Session["lname"].ToString();

    // Response.Write(uname);
    // uname = "sri hari";
    uname = uname + " ";
    string uname1 = uname;
    uname = uname.Trim();
    SqlCommand cmd = new SqlCommand("insert into qry_details values('" + txt_query_name.Text + "','pending for approval','" + txt_query_description.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + qry + "','" + uname1 + "')", con);
    cmd.ExecuteScalar();
}
4

3 回答 3

26

检查 qry_details 表的长度,看看它是否小于您发送到数据库的字符串?

基本上例外是说你正在尝试比列长度更大的东西。

于 2013-06-26T06:04:07.390 回答
10

我建议您使用参数化查询。您的代码现在容易受到 SQL 注入的攻击。此外,您应该ExecuteNonQuery在 SQL 命令上使用该方法,而不是ExecuteScalar在向数据库插入值时使用:

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();
}
于 2013-06-26T06:04:04.420 回答
1

当插入值大于 SQL Server 上表中定义的字段宽度时,通常会发生此错误。

检查您是否使用 DateTime.Now c# 函数插入日期和时间,您的表必须是 DateTime 类型。不仅仅是日期或时间。

于 2016-09-17T09:58:30.203 回答