Reputation: 63
I am creating a web application/website using ASP.net in visual studio 2010. We have our basic website and I even created a SQL Server database which is in the App_Data
folder of my web application folder.
I created tables and a few procedures, but I do not know how to have my web forms or their controller (C#) classes access the tables. Below is my rough setup to access it. I don't know what to set the string to equal. The database is in webapplication1/App_Data/database.mdf
.
The file I want to access it is webapplication/App_Code/DataConnect.cs
. What should the string equal. What do I need to do to test it?
{
SqlConnection _sqlConn = null;
string _connectionString = ?
_sqlConn2 = new SqlConnection(_connectionString);
_sqlConn.Open();
}
Upvotes: 4
Views: 46775
Reputation: 399
You can manually write connection string into your code...
string strcon = @"Data Source=SERVERNAME; Initial Catalog=DATABASENAME; Integrated Security=True";
OR
Follow below steps to connect local SQL Server database...
Check below link for more understanding....
Upvotes: 3
Reputation: 1
string _connectionString =@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"
Upvotes: 0
Reputation: 293
the connection string just like
string _connectionString =@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"
if you have any connection string problem, please refer to http://www.connectionstrings.com/
Upvotes: 0
Reputation: 4469
You can try with below ways:
string _connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename="+
Server.MapPath("~/App_Data")
+@"\database.mdf;Integrated Security=True;User Instance=True"
Or
string _connectionString =@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True;User Instance=True"
Upvotes: 0
Reputation: 94653
You may use following connection string.
string _connectionString =@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
You can also add the connection string into web.config's connectionString section and later use it in code.
<connectionStrings>
<add name="CnStr"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
To retrieve connectionString from web.config
string _connectionString=System.Configuration.ConfigurationManager.ConnectionStrings["CnStr"].ConnectionString;
Upvotes: 7