Reputation: 901
How can I connect to database using sql server authentication programmatically in c# winforms? I mean i created a login named loginTesting with a loginTesting as user in sql server 2012. I want to access that login in c# by accepting user inputs from textbox. Thanks.
Upvotes: 0
Views: 3842
Reputation: 2152
You can use the class SqlConnectionStringBuilder to construct the connection string that you will need for a SqlConnection object:
SqlConnectionStringBuilder scsBuilder = new SqlConnectionStringBuilder();
scsBuilder.UserID = "username";
scsBuilder.Password = "password";
scsBuilder.DataSource = "servername or ip address";
scsBuilder.InitialCatalog = "databasename";
scsBuilder.IntegratedSecurity = false;
using (SqlConnection sqlCon = new SqlConnection(scsBuilder.ConnectionString))
{
// perform your SQL tasks
}
Further reading here:
SqlConnectionStringBuilder Class
SqlConnection Class
Upvotes: 3
Reputation: 46
Expanding on Answer 1, if you'd like to test your usernames/passwords based on user input you could use the SqlConnectionStringBuilder object as shown in this example:
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
connectionString.ConnectionString = @"data source=.;initial catalog=master;";
connectionString.UserID = "username";
connectionString.Password = "password";
using (var sqlConnection = new SqlConnection(connectionString.ConnectionString))
{
}
Upvotes: 2
Reputation: 34539
You need to create a new SQLConnection (and clear it up once you've used it).
using(var connection = new SqlConnection(connectionString))
{
// Do something
}
The tricky bit is getting the correct connection string, but fortunately there are resources to help. Checkout ConnectionStrings.com to find a connection string that looks like it should work, plug in your credentials/server etc and you're good to go.
Upvotes: 0