Reputation: 6282
I am currently trying to establish a connection between an ASP.NET web site project and a Database built by SQL Server 2008 R2.
The way I am required to do so is to use the connectionString
from the Web.config
page, but I have no idea what value to give it or how to establish a connection using said value. (Using C#)
Any help would be appreciated, as I found next to no information about the subject.
Here is the (default) value that is currently in the Web.config
page:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Upvotes: 3
Views: 34410
Reputation: 8598
Use Configuration Manager:
using System.Data.SqlClient;
using System.Configuration;
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using(SqlConnection SqlConnection = new SqlConnection(connectionString));
//The rest is here to show you how this connection would be used. But the code above this comment is all you really asked for, which is how to connect.
{
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
SqlCommand SqlCommand = new SqlCommand();
SqlConnection.Open();
SqlCommand.CommandText = "select * from table";
SqlCommand.Connection = SqlConnection;
SqlDataReader dr = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
Upvotes: 5
Reputation: 100248
string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
// command.Parameters.AddWithValue("@param", value);
connection.Open();
command.ExecuteNonQuery(); // or command.ExecuteScalar() or command.ExecuteRader()
}
Upvotes: 0
Reputation: 14460
This article about Connect to SQL Server Using SQL Authentication in ASP.NET will probably give you a better idea of what need to be done.
As a pre check, just check if your mssqlserver
services are running.
Upvotes: 0