【问题标题】:SqlException was Unhandled An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dllSqlException 未处理 System.Data.dll 中发生了“System.Data.SqlClient.SqlException”类型的未处理异常
【发布时间】: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();这条线失败了。 @jdweng​​span>

标签: c# sql winforms


【解决方案1】:

不要忘记在连接字符串中包含数据库的名称(初始目录)。

connetionString = "Data Source=desktop-brvgrif\sqlexpress;Initial Catalog=MyDatabaseNameHere;Integrated Security=True";

Connection String Syntax

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多