4334738290
4334738290

Reputation: 393

Connecting to local database

I am trying to create to a local database via a mdf file, like so:

scon = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDBFilename=|DataDirectory|\articles.mdf; Integrated Security=True");
scon.Open();
scmd = new SqlCommand("Insert INTO articles(url) VALUES(@url)");
scmd.Parameters.AddWithValue("@url", "http://google.com");
scmd.ExecuteNonQuery();

MY mdf file is in the root folder, and in the debug folder too. When I run the following code I get an error saying the following:

enter image description here

I can't use the full connection path because it's a long url with spaces, here is my file structure:

enter image description here

My database exists:

enter image description here

How can I fix this so I can connect to my database?

Upvotes: 0

Views: 104

Answers (2)

Mostafa Mohamed Ahmed
Mostafa Mohamed Ahmed

Reputation: 649

The Problem With Your Code Is That You Have A Command and a Connection But There Is Nothing To Till The Command To Use This Connection Object ... You Can Use The SqlCommand Constructor To Do That

scmd = new SqlCommand("Insert INTO articles(url) VALUES(@url)",scon)

Or Use The Connection Property Of The SqlCommand Class Like This

scmd.Connection = scon  

Consider Adding Using To Your SQL Connection ... Or Else You Will Have To Manually Close The Connection By Calling scon.Close(); if You Didn't Do either Of Those You Will Run Into An Exception If Your Tried To Open The Connection Again While It's Already Open

Upvotes: 0

Steve
Steve

Reputation: 216343

Pass the connection object to the SqlCommand constructor

scmd = new SqlCommand("Insert INTO articles(url) VALUES(@url)", scon);

The connectionstring is fine, the error message informs you that it is not possible to execute a command if the database is not known. The SqlConnection contains this information and you need to pass it to your command. Another possibility is through the

scmd.Connection = scon;

but, personally, I prefer to pass that info in the constructor.

Final but really important note:
SqlConnection and SqlCommand are disposable objects. You should always dispose these kind of objects. The using statement is the correct method

using(scon = new SqlConnection(....))
using(scmd = new SqlCommand("Insert INTO articles(url) VALUES(@url)",scon))
{
   scon.Open();
   scmd.Parameters.AddWithValue("@url", "http://google.com");
   scmd.ExecuteNonQuery();
}

Upvotes: 3

Related Questions