Database Connection with Asp.net MVC
How to make Database connection in ASP.Net/MVC project ?
Open Web.config file from your project and then you will find <connectionStrings> tag here under <configuration> tag
Your can write multiple connection strings here (Different database connection) like in figure two of the connection string are there. In connection strings you have to write the following item:
- name: write the name of connection whatever you want
- Data Source: its your server name/local computer name
- Initial Catalog: write you database name
- ID: sa (sa is the default name if you select Mixed mood will installing sql server)
- Password: write password you give at the time of sql installation
Note: if you select window authentication in sql server then don’t provide ID and Password in connection string
Confirm your server name etc from your SQL Server
Following is the connection string if in your Web.congi file if its dont contain <connectionStrings> section just copy the following code and past in <configuration> section before <appSettings> section
<connectionStrings>
<add name=”SqlConnection” connectionString=”Data Source=DESKTOP-NMIBRCO\MYSQL;Initial Catalog=Pickbuy; Password=comsats;User ID=sa;Integrated Security=True” providerName=”System.Data.SqlClient” />
</connectionStrings>
write the following code in any of your class to get the connection string in any variable just here the variable name is conString
string ConString=ConfigurationManager.ConnectionStrings[“SqlConnection”].ConnectionString;
How to test a database connection?
- Create a empty notepad file on your computer desktop and save as with the name test. udl
- Double-click the test.udl
- Click the Provider tab.
- Select Microsoft OLE DB Provider for SQL Server.
- Click Next.
- On the Connection tab, enter the connection information server name, credential and database name
- Click Test Connection.
If connection is successful the system promote the success message else error message
Don’t write anything in notepad just save with anyname.udl after saving the file open udl extension file the following view open to select and fill the connection credential
After filling the things click on Test Connection