Control Freak
Control Freak

Reputation: 13233

Connection string was not found

I am trying to run this code:

var db = Database.Open("DBNAME");
var q  = "Select Name From Table";

@foreach(var row in db.Query(q)){
      <li> @row.Name </li>
}

But I get the error System.InvalidOperationException: Connection string "DBNAME" was not found.

So I went in to WebMatrix 3 and added this database under Other Connections and working fine in the WebMatrix3 app. But the connection string I fed WebMatrix to add to the connections was not appended to the web.config file, and I still get this error, so not sure what else to do? Suggestions?

Also, do DB connections like this have to be closed? I did not see a close statement in the example I took this from, which is from here: http://www.w3schools.com/aspnet/webpages_database.asp


Update: I added the following setting in web.config:

 <connectionStrings>
   <add name="DBNAME" connectionString="server=(local)\Server;database=DBNAME;uid=myUser;password=myPass;" />
 </connectionStrings>

And now I get the following error instead: System.ArgumentException: Keyword not supported: 'server'. <-- this error shows up for the @foreach line

Upvotes: 0

Views: 7716

Answers (1)

Tomi Niemenmaa
Tomi Niemenmaa

Reputation: 650

You can just add the connection string to your web.config file. Depending on what kind of database you use.

If you use SQL Server you can use something like this:

<configuration>
   <connectionStrings>
      <add name="DBNAME" connectionString="Data Source=.\Server;Initial Catalog=MyDatabase;User ID=Username;Password=Password" providerName="System.Data.SqlClient"/>
   </connectionStrings>
<configuration>

More on connection strings here: http://www.connectionstrings.com/

Edit:

Yes Database connection should be closed! It implements IDisposable interface so you should use the using clause.

Here is an example

using (Database db = Database.Open("DBNAME"))
{
   // Do your database stuff here
}

It will call the Dispose mehtod when it reaches the end of using clause. Dispose() will close the connection upon many other things.

Upvotes: 5

Related Questions