Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to local SQL Server database using C#

Tags:

c#

sql-server

Suppose I have created a SQL Server database called Database1.mdf in the App_Data folder in Visual Studio with a table called Names.

How could I establish a connection to read the table values using C#?

So far I've tried something like this:

SqlConnection conn = new SqlConnection("Server=localhost;Database=Database1;");

conn.Open();

// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Names";

But I get an error:

database not found/error connecting to database

like image 979
Tony Avatar asked Aug 31 '12 18:08

Tony


1 Answers

In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

like image 64
Mohamad Y. Dbouk Avatar answered Sep 21 '22 06:09

Mohamad Y. Dbouk