Why I can not get requested data when I open connection?

Sajo_Nez1510 21 Reputation points
2021-07-20T08:40:05.367+00:00

Hello. I want to open a connection to a local server, the NORTHWND database. When I open the connection it does not print the desired data I requested below.I do not get anything. Just black window on console when I run code. I think there is some problem with opening connection but I can not figure it how to solve it.Here is the code

using System;
using System.Linq;
using System.Configuration;

using System.Data.SqlClient;
using Microsoft.IdentityModel.Protocols;

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
try
{
using (sqlConnection)
{
sqlConnection.Open();
Console. WriteLine("State of connection {0}", sqlConnection.State.ToString());
Console.WriteLine("Name of Base {0}", sqlConnection.Database);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
sqlConnection.Close();
}

    }  
}  

}

//Here is the code of configuration file which is in another file on the same project:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Northwind" connectionString="Data Source=.;Initial Catalog=NORTHWND;Integrated Security=SSPI"/>

</connectionStrings>  
</configuration>  

116282-pic3.png

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,838 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,626 Reputation points
    2021-07-21T02:42:26.563+00:00

    Hi SajoNez1510-5981,
    Is the connection status and database name correctly output when the project is running? If not, what is wrong with the code.
    I used your code to do a test and it can output correctly, the only difference is the connection string.
    I followed the steps below to get the connection string. You can refer to the following:
    View->SQL Server Object Explore->Right click my Database name->Properties->Connection String-> Copy it to configuration file.
    116550-721.png
    Here is test result:

    116591-7211.png

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.