如何将数据插入表中 [英] How do I insert data into table

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

问题描述

我在c#中使用此代码以编程方式将数据插入表中:



I have this code in c# to insert data into table programmatically:

 using (SqlConnection conn = new SqlConnection(@"Data source = xxxx; Database=xxxxx; User Id=xxxx; Password=xxxx"))
{
 conn.Open();
 string sqlQuery = @"INSERT INTO UXFaturas(TransDocument, TransSerial, TransDocNumber, 
 Data, Estado) VALUES (@transdocument, @transserial, @transdocnumber, @data, @estado)";
 MessageBox.Show("step1");
 SqlCommand SQLcm = new SqlCommand();
 SQLcm.Connection = conn;
 SQLcm.CommandText = sqlQuery;
 SQLcm.CommandType = CommandType.Text;
 MessageBox.Show("step2");
 SQLcm.Parameters.AddWithValue("@transdocument", transdocument);
 SQLcm.Parameters.AddWithValue("@transsarial", transserial);
 SQLcm.Parameters.AddWithValue("@transdocnumber", transdocnumber);
 SQLcm.Parameters.AddWithValue("@data", data);
 SQLcm.Parameters.AddWithValue("@estado", estado);
 MessageBox.Show("step3");
 SQLcm.ExecuteNonQuery();
 MessageBox.Show("inseriu");
 conn.Close();
}





我的尝试:



我添加了三个messagebox.show();以了解程序停止工作的位置,但它完成了所有三个步骤,只是跳过了SQLcm.ExecuteNonQuery();.

如果需要,我可以提供创建表和变量的代码。



What I have tried:

I've added the three messagebox.show("");to know where the program stops working but it goes through all three steps and just skips the SQLcm.ExecuteNonQuery();.
I can provide the code to create the table and the variables if you need.

推荐答案

可能与您的请求有关的事情是失败的,那就是抛出正在其他地方捕获的异常。

将行更改为:

Chances are that something to do with your request is failing and that is throwing an exception that is being caught elsewhere.
Change the line to this:
rowsAffected = SQLcm.ExecuteNonQuery();



并在方法的顶部添加以下行:


And add this line at the top of the method:

int rowsAffected = -1;



现在将该代码包含在 try ... catch 块中在ExecuteNonQuery行上添加断点,在 catch 块中添加断点。

在调试器中再次运行代码(可以删除Mes sageBoxes for this)并观察会发生什么。当您运行 ExecuteNonQuery 语句时,将发生以下两种情况之一。第一个是控件将移动到 catch 块,您可以查看异常详细信息以了解原因。另一种是 rowsAffected 将被设置为插入的行数。如果是1,那就好了。如果不是......好吧,捕获块应该抓住了它!



试试看,你看到了什么。


Now encase that code in a try...catch block and add breakpoints on the ExecuteNonQuery line, and inside the catch block.
Run your code again inside the debugger (you can remove the MessageBoxes for this) and watch what happens. When you run the ExecuteNonQuery statement, one of two things will happen. The first is that control will move to the catch block, and you can look at the exception detail to see why. The other is that rowsAffected will get set to the number of rows inserted. If that's 1, then fine. If not ... well, the catch block should have caught it!

Try that, and see what you find.


这篇关于如何将数据插入表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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