简体   繁体   中英

C# and SQL Server 2008 R2: Finding DB Address and connection string

I have SQL Server 2008 R2 installed and have the necessary databases created. Now I am trying to connect to the server through C# and failing miserably. I have tried several connection string formats from connectionstrings.com, but I still cannot connect to the database. This is the format I'm assuming I'm to use:

        public static void connect()
        {
        string conString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword"; 

        SqlConnection con = new SqlConnection(conString);
        try
        {
            con.Open();
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to connect to database");
        }
    }

But I can't seem to identify the correct address and authentication (using windows authentication). How can I find the address in MSSM, and how would I properly use windows authentication?

Thanks so much.

Note: I am using Visual Studio 2010

Josh, you may want to consider using System.Data.SqlClient.SqlConnectionStringBuilder so you don't have to worry about the correct format.

edit: and when I actually look at your connection string, you say you're attempting Windows Authentication, but you provide a username and password. Instead, you want to do something like this:

Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

I found a way to cheat and find the connection string. Adding a new ADO.NET Entity Data Model in Visual Studio 2010 and importing a database from SQL 2008 R2 actually lists the connection string in the dialog box! I'm still going to use the SqlConnectionStringBuilder, but now I have the elements I need. Thanks for the input!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM