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

问题描述

每次运行程序时都会说



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();
}

推荐答案



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*/))


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

09-02 00:48