Connecting to the Database
To connect to a database in an ASP.NET application, you’ll first need to have a SQL Server instance set up, with the database that you want to connect to already created. Once you have a database set up, you can follow these general steps to connect to it from your ASP.NET code:
Add a connection string to your web.config file that specifies the server name, database name, and any other necessary connection parameters. For example:
<connectionStrings>
<add name=”MyConnectionString” connectionString=”Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True;” providerName=”System.Data.SqlClient” />
</connectionStrings>
Replace SERVERNAME and DATABASENAME with the appropriate values for your SQL Server instance and database, respectively.
In your application code, create an instance of the SqlConnection class and pass in the connection string:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[“MyConnectionString”].ConnectionString);
Open the connection:
connection.Open();
Use the connection object to execute SQL commands against the database, such as queries or updates:
SqlCommand command = new SqlCommand(“SELECT * FROM Customers”, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// do something with the data
}
Close the connection when you’re finished:
connection.Close();
Note that in this example, I’ve used Integrated Security=True in the connection string, which means that the connection will use Windows Authentication to log in to the database. If you need to use SQL Server authentication instead, you’ll need to include a User ID and Password in the connection string. Also, be sure to replace “Customers” in the example query with the appropriate table or view name from your database that you want to work with.
Apply for ASP.NET Certification Now!!
https://www.vskills.in/certification/certified-aspnet-programmer