SqlException未处理System.Data.dll中发生了类型为'System.Data.SqlClient.SqlException'的未处理异常

时间:2019-04-02 14:19:55

标签: c# sql winforms

我正在用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();

1 个答案:

答案 0 :(得分:1)

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

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

Connection String Syntax