question

SajoNez1510-5981 avatar image
0 Votes"
SajoNez1510-5981 asked DanielZhang-MSFT commented

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

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


dotnet-adonet
pic3.png (168.0 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @SajoNez1510-5981,
May I know whether your issue has been solved or not? If not, please share it in here. We can work together to figure it out.
Best Regards,
Daniel Zhang

0 Votes 0 ·

1 Answer

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered

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.



721.png (25.8 KiB)
7211.png (4.8 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.