如何从Database.ExecuteNonQuery获取输出? [英] How do I get the output from Database.ExecuteNonQuery?
问题描述
我想使用Database.ExecuteNonQuery或类似的方法来执行sql脚本,然后捕获输出.
例如:xxx表已创建
我的脚本:
strArray = Regex.Split(streamReader.ReadToEnd(), "\r\nGO");
if (connection.State == ConnectionState.Open)
{
System.Data.SqlClient.SqlCommand cmd;
foreach (string sql in strArray)
{
cmd = new System.Data.SqlClient.SqlCommand(sql);
cmd.Connection = connection;
Console.WriteLine(sql);
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
}
}
如果我理解正确,我想你的意思是检索发出sql命令的信息性消息".我没有尝试过,但是我认为打印语句"结果的处理方式相同.在这种情况下,您需要向SQL连接对象添加一个信息性事件处理程序.
请参见本文,其中介绍了如何执行此操作. /p>
非常简单(片段是从aticle抓取的)
myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
myStringBuilderDefinedAsClassVariable.AppendLine(e.Message);
}
I would like to use the Database.ExecuteNonQuery or something similar to execute a sql script and then capture the output.
eg: xxx Table created
My script:
strArray = Regex.Split(streamReader.ReadToEnd(), "\r\nGO");
if (connection.State == ConnectionState.Open)
{
System.Data.SqlClient.SqlCommand cmd;
foreach (string sql in strArray)
{
cmd = new System.Data.SqlClient.SqlCommand(sql);
cmd.Connection = connection;
Console.WriteLine(sql);
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
}
}
If I understand correctly, I think you mean to retrieve the "informational messages" that come from issuing a sql command. I have not tried, but I think the "print statements" results are handled the same way. In which case, you need to add a informational event handler to your sql connection object.
See this article which explains how to do this.
Pretty simple (snippet grabbed from aticle)
myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
myStringBuilderDefinedAsClassVariable.AppendLine(e.Message);
}
这篇关于如何从Database.ExecuteNonQuery获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!