I'm using MS Visual Studio 2010 to create an application with SQL Server 2008 database access, but what I did to create the database was add a new "SQL Server 2008 Database Project", it added it, and shows me everything on my Solution Explorer, but how do I write the connection string to connect to it, because I wrote this one, and it didn't work.
SqlConnection cnTrupp = new SqlConnection("Initial Catalog = Database;Data Source = localhost;Persist Security Info=True;");
update:
I used this one:
cnTrupp = new SqlConnection("database=DB_Trupp;server=.\\SQLExpress;Persist Security Info=True;integrated security=SSPI");
But when I use the cnTrupp.Open()
it tells me that the login failed.
This question is related to
c#
sql
visual-studio-2010
Copy/Paste what is below into your code:
SqlConnection cnTrupp = new SqlConnection("Initial Catalog = Database;Data Source = localhost;Persist Security Info=True;Integrated Security = True;");
Keep in mind that this solution uses your windows account to log in.
As John and Adam have said, this has to do with how you are logging in (or not logging in). Look at the link John provided to get a better explanation.
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
Standard Security
Data Source=serverName\instanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Data Source=serverName\instanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;
Here's a good reference on connection strings that I keep handy: ConnectionStrings.com
Instead of writing it in your code directly I suggest you make use of the dedicated <connectionStrings>
element in the .config file and retrieve it from there.
Also make use of the using
statement so that after usage your connection automatically gets closed and disposed of.
A great reference for finding connection strings: connectionstrings.com/sql-server-2008.
Source: Stackoverflow.com