我正在使用SMO
我很难捕获结果(可能是语法错误消息或数据结果集)就像我们进入SQL Server Management Studio一样。我尝试了几个我在互联网上找到的例子,但是无法按照我的意愿使它工作。
我尝试了以下两种语法
//I am trying catch errors here
int[] results = DBServer.ConnectionContext.ExecuteReader("select * from SomeNonExistingTable");
//I am trying to catch result sets as dataset here
//But I cannot implicitly convert to dataset here using C#
DataSet ds = databaseServer.ConnectionContext.ExecuteWithResults("Select * from mytable");
我试图从以下网站获得一些想法:
SMO ConnectionContext.StatementTimeout setting is ignored
Using SMO, still no go... ConnectionContext.ExecuteNonQuery(script) can't understand "GO"
答案 0 :(得分:2)
您可以加入try
和catch
。
try {
DBServer.ConnectionContext.ExecuteReader("select * from SomeNonExistingTable");
}
catch(Exception ex) {
while(ex.InnerException) {
err = ex.InnerException;
Console.WriteLine(err);
}
}
答案 1 :(得分:0)
在控制台应用程序C#中,这是一个有效的例子:
var server = new Server(@"YourServer");
server.ConnectionContext.DatabaseName = "YourDatabase";
try
{
var result = server.ConnectionContext.ExecuteReader("SELECT * FROM YourTable");
while (result.Read())
{
Console.WriteLine(result["ValidColumn"]);
}
}
catch (Exception ex)
{
// error handling
Console.WriteLine(ex);
}
try
{
var result = server.ConnectionContext.ExecuteWithResults("SELECT * FROM YourTable");
var i = 0;
while (i < result.Tables[0].Rows.Count)
{
var dr = result.Tables[0].Rows[i];
Console.WriteLine(dr["ValidColumn"]);
i++;
}
}
catch (Exception ex)
{
// error handling
Console.WriteLine(ex);
}
Console.ReadLine();