【发布时间】:2019-04-02 14:19:54
【问题描述】:
我正在使用 C# 和 SQL 学习 WinForms。当我执行代码时,我得到了这个错误: "System.Data.dll 中发生了 'System.Data.SqlClient.SqlException' 类型的未处理异常"
代码如下:
string connetionString;
SqlConnection cnn;
connetionString = @"Data Source=desktop-brvgrif\sqlexpress;Integrated Security=True";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "SELECT TutorialID,TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while(dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "\n";
}
MessageBox.Show(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
【问题讨论】:
-
在这段代码周围使用 try/catch ... 并找到有关异常的更多信息 ... 题外话:你知道 using/IDisposable 吗?
-
你能告诉我如何用 try/catch 包围吗? @塞尔文
-
哪行代码失败了?
-
IDisposable 是一种在应用程序中释放非托管资源的机制。
-
dataReader = command.ExecuteReader();这条线失败了。 @jdwengspan>