Can anyone help me out please? I'm confused.
I want to set up my connection string so I can just call it from my Web.Config file.
I need a way to call it from my code, please make a little example. :(
I also need help on setting up the Web.Config file.
I don't know what properties to use. Here's a screenshot of what my credentials are. I have no password set up for Windows. I'm really lost here.
After opening the web. config file in application, add sample db connection in connectionStrings section like this: <connectionStrings>
You can either use the new operator to make that directly. For example: SqlConnection conn = new SqlConnection( new SqlConnectionStringBuilder () { DataSource = "ServerName", InitialCatalog = "DatabaseName", UserID = "UserName", Password = "UserPassword" }. ConnectionString );
and read from it like this: string strcon = ConfigurationManager. ConnectionStrings["Dbconnection"]. ConnectionString; SqlConnection DbConnection = new SqlConnection(strcon);
Here's a great overview on MSDN that covers how to do this.
In your web.config, add a connection string entry:
<connectionStrings> <add name="MyConnectionString" connectionString="Data Source=sergio-desktop\sqlexpress;Initial Catalog=MyDatabase;User ID=userName;Password=password" providerName="System.Data.SqlClient" /> </connectionStrings>
Let's break down the component parts here:
Data Source is your server. In your case, a named SQL instance on sergio-desktop
.
Initial Catalog is the default database queries should be executed against. For normal uses, this will be the database name.
For the authentication, we have a few options.
User ID and Password means using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database. All the basic dialogs are very self-explanatory.
You can also use integrated security, which means your .NET application will try to connect to SQL using the credentials of the worker process. Check here for more info on that.
Finally, in code, you can get to your connection string by using:
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With