How do I get the output from Database.ExecuteNonQuery?

我们两清 提交于 2019-12-10 15:58:13

问题


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

回答1:


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



回答2:


ExecuteNonQuery return an int based on the number of rows affected and is used for UPDATE, DELETE and INSERT.

See the MSDN documentation

SqlCommand.ExecuteNonQuery Method

You want ExecuteScalar



来源:https://stackoverflow.com/questions/19938971/how-do-i-get-the-output-from-database-executenonquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!