我想根据用户输入在表中插入一些值。我从一些文本框中获取这些值。当我在SQL逻辑之前放置一个断点,并通过F10遍历每一行时,一切正常。我打开SQLConnection
,创建一个SQLCommand
,执行它,然后再次关闭连接。我刷新表并在那里拥有所有值。但是当我删除或禁用断点,并且程序自身遍历这些代码行时,它不起作用,这意味着无论我多久刷新一次,都不会向表中添加任何值。
以下是我所指的代码:
try
{
SqlConnection con = new SqlConnection("Server=...;Database=...;Integrated Security=true;");
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO TestTable (Type,Serialnumber) VALUES('" + TypeText + "','" + SerText + "')", con);
//Debug.WriteLine(com.CommandText);
com.BeginExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
答案 0 :(得分:1)
当它自己运行时,它会调用BeginExecuteNonQuery()
并关闭右下一行连接而不等待异步调用结束。在使用调试器执行F10时,您可以有时间有效地结束执行。请考虑使用ExecuteNonQuery()
,注意缺少Begin。
答案 1 :(得分:0)
BeginExecuteNonQuery方法启动异步执行不返回行的Transact-SQL语句或存储过程的过程,以便在执行语句时可以同时运行其他任务。语句完成后,开发人员必须调用EndExecuteNonQuery方法来完成操作。 BeginExecuteNonQuery方法立即返回(CommandTimeout对BeginExecuteNonQuery没有影响),但是在代码执行相应的EndExecuteNonQuery方法调用之前,它不能执行任何其他对同一SqlCommand对象启动同步或异步执行的调用。在命令执行完成之前调用EndExecuteNonQuery会导致SqlCommand对象阻塞,直到执行完成。
答案 2 :(得分:0)
在编写任何DML代码之前,您需要考虑很多事情,请考虑下面的链接,它为您提供了处理资源的方法。
答案 3 :(得分:0)
最好与ExecuteNonQuery
一起使用,而不是BeginExecuteNonQuery
try
{
using (SqlConnection conn = new SqlConnection("your Connection string"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"INSERT INTO TestTable
(Type,Serialnumber )
VALUES (@type,@serialnumber)";
cmd.Parameters.AddWithValue("@type", type);
cmd.Parameters.AddWithValue("@serialnumber", serialnumber);
int rows = cmd.ExecuteNonQuery();
if (rows == 0)
throw new Exception("Nothing Inserted into the DB");
}
}
}
catch (Exception ex)
{
}