插入数据库时​​出错 [英] Error when inserting in database

查看:75
本文介绍了插入数据库时​​出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次运行程序时都会说



System.Data.dll中出现未处理的System.Data.SqlClient.SqlException异常



附加信息:字符串或二进制数据将被截断。



该语句已被终止。



请保持简单的解决方案,我是C#的新手。



我是什么尝试过:



Everytime when I run the program it says

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: String or binary data would be truncated.

The statement has been terminated.

Please keep it simple in the solutions, i'm kinda new to C#.

What I have tried:

private void button1_Click(object sender, EventArgs e)
{
 con = new SqlConnection("The Database connection string")
 con.Open();
 cmd = new SqlCommand("INSERT INTO Storage (Serial,Name) VALUES (@Serial,@Name)",     con);
 cmd.Parameters.Add("@Serial", txtSerial.Text);
 cmd.Parameters.Add("@Name", txtName.Text);
 cmd.ExecuteNonQuery();
}

推荐答案

可能是Serial或Name中至少有一个长度为>数据库表列。
Hi, it could be that at least one of Serial or Name has length > database table column.


字面上的错误消息说:您正在尝试插入一个字符串或二进制数据,该数据长于为目标字段设置的最大长度。你必须找出哪个领域是罪魁祸首。要解决此问题,您可以根据需要更改该字段允许的最大长度或通过验证限制输入数据的长度。
Literally as the error message said: you are trying to insert a string or binary data that is longer than the max length set for the target field. You have to find out which field is the culprit. To resolve this, you may change the max length allowed for that field or limit the length of the input data through validation, depending on your requirements.


try
           {
               using (SqlConnection connection = new SqlConnection(connectionString))
               {
                   using (SqlCommand cmd = new SqlCommand("INSERT INTO Storage (Serial,Name) VALUES (@Serial,@Name)", con))
                   {
                       connection.Open();
                       cmd.Parameters.Clear();
                       cmd.Parameters.Add("@Serial", txtSerial.Text);
                       cmd.Parameters.Add("@Name", txtName.Text);
                       int res=cmd.ExecuteNonQuery();
                       if (res > 0)
                       {
                           MessageBox.Show("Done");
                       }
                       else
                       {
                           MessageBox.Show("Error");
                       }

                       connection.Close();
                   }

               }
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }





请在连接变量名之后使用sql quary







please use sql quary after connection variable name like this


using (SqlCommand cmd = new SqlCommand("INSERT INTO Storage (Serial,Name) VALUES (@Serial,@Name)", ******** /*this place*/))


这篇关于插入数据库时​​出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆