Create a sql connection string to locate an mdf database [duplicate] - c#

Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.

A great resource I always keep around is connectionstrings.com.
It's really handy for finding these connection strings when you can't find an example.
Particularly this page applied to your problem
Attach a database file on connect to a local SQL Server Express instance
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

So here's the answer from MSDN:
Choos[e] "Add New Data Source" from the
Data menu.[And follow the connection wizard]
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
Click on Tools >> Connect to Database...
Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "AttachDbFilename" attribute and value. Example:
The raw text from the Advanced panel:
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
The actual entry in the web.config:
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />

Just one more -- i've always kept a udl file on my desktop to easily create and test connection strings. If you've never done it before - create a new text file and name it to connection.udl (the ext is the only important part). Open the file, start on the Provider tab and work your way through. Once you're happy with the connection rename the file giving it a .txt extension. Open the file and copy the string - it's relatively easy and lets you test the connection before using it.

<add name="Your Database" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Expanse.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>

In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add
string constr = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=|DataDirectory|\myData.mdf; Integrated Security=True; Connect Timeout=30;";
using (SqlConnection conn = new SqlConnection(constr))
string constr = ConfigurationManager.ConnectionStrings["myData"].ToString();
using (SqlConnection conn = new SqlConnection(constr))
{
sqlQuery=" Your Query here"
SqlCommand com = new SqlCommand(sqlQuery, conn);
com.Connection.Open();
string strOutput = (string)com.ExecuteScalar();
}

Related

Connect to a SQL Server database without a set file path

I am attempting to connect to a local SQL Server database in C#.
I am currently using the following connection string:
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\majorWork\majorWork\gameStats.mdf;Integrated Security=True";
However, I do not want to use a hardcoded file path, as I wish to be able to use the application across multiple computers, where the file path will be different. How should I go about doing this?
Best way is set this connection in Web.Config file.
<Database>
<ConnectionString name="connection">Server=servername; Initial Catalog=dbname; Persist Security Info=False; User ID=username; Password=password; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30;;</ConnectionString>
</Database>
Then add Add System.Configuration as a reference.
in C# you can call this
string constring = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
After that you can create new connection instance by passing this to
SqlConnection con = new SqlConnection(constring)
If u install SQL server express using the default instance, then you can connect using . as your server name anyone can use it with default instance as well.
1.then in visual studio, click on solution explorer
2. Connect database, follow the instruction for SQL server
3. When it gets to server name use . to connect and choose your database name which you have created already in ms SQl, then test your connection
4. After it successful, u can now click on the database name showing under solution explorer,
5.after u click the database name, at the button right corner, there will be a connection string, copy it and use
This will be declared publicly or globally
Sqlconnection con = new sqlconnection("paste the connection string");
And to use
Sqlcommand cmd = new sqlcommand("insert into......",con);
Con.open ();
Cmd.executenonquery();
Con.close();

How to create connection for mdf files

I am creating a Windows application with a local database.
Now I need to define a connection string for that local database in C#.
What is the connection string for local .mdf files in Winforms C#?
Do the following steps:
In your Server Explorer window right click on the database that
you've created and select Properties.
in the Properties window copy the value of the connection string
property and paste it to your application.
It should be something like this:
Data Source=(localdb)\v11.0;Initial Catalog=yourDB;Integrated Security=True
Just you need to add one extra \ to it to work in c#:
string address = "Data Source=(localdb)\\v11.0;Initial Catalog=yourDB;Integrated Security=True";
You could also have a look at
The Connection Strings Reference.
Here you go
<add name="YourDataBase" connectionstring="Data Source=.\SQLEXPRESS; AttachDbFilename=Path\YourDataFile.mdf; Integrated Security=True; Connect Timeout=30; User Instance=True" />
Also you can visit connectionstring.Com as well for more.
Use SqlServeCe as a namespace and then give the following codings
using System.Data.SqlServerCe;
SqlCeConnection conn = new SqlCeConnection(#"Data Source=D:\PROJECT\data\db.mdf;");

Windows Form Application and SQL Server

UPDATE 2
I fixed the error by adding System.Configuration to the reference file. I had already added it to my class with using System.Configuration;
I found the answer here: The name 'ConfigurationManager' does not exist in the current context
Any further issues will be addressed in a new question.
Original(ish) Post
I have Microsoft SQL Server Management Studio. In the studio I created a database called Logbook that exists locally on my computer.
I have also created a user interface using a Windows forms application in VS C# Express. I would like to connect it to my logbook database in order to update, select, delete, and insert entries into the database through the UI.
However, I cannot figure out how connect the two. I have played around with the "Add new data source" wizard to no avail. I also cannot find anything helpful in the MSDN or other tutorials online.
UPDATE
I created a new database and project to work with until I figure out how to properly do this so I don't accidently break anything in my project.
The Schema is:
Student(sid: int, fname: char(10), lname: char(10), age:int, major:char(10))
Course(cid:int, desc:char(50), dept:char(10))
Enrolled(sid:int, cid:int, quarter:char(10), grade:char(10))
Here is the connection string generated by the "Add Data Source" wizard
<add name="boathouseLogConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\boathouseLog.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
I have successfully gotten my database into the project. However, when I try running a stored procedure I get this error Argument Exception was unhandled. Format of the initialization string does not conform to specification starting at index 0.
The error occurs on line 2.
DataTable dt = new DataTable();
SqlConnection sqlConn = new SqlConnection(selectedConnectionString);
SqlCommand myCommand = new SqlCommand("proc_getMember", sqlConn);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
the selectedConnectionString variable is set to boathouseLogConnectionString
Initial Hints
If you want to see some examples for windows forms connecting to a database i can recommend the forms over data video series. Video 2 is about how to connect to a database.
In the app.config file you can put your connection data
<connectionStrings>
<add name="OrderManager.My.MySettings.OMSConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\OMS.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
To be able to help you better i need more details. If you connect in management studio you can take a look at your connections properties. What are the values here and so on.
Update
There is another question with a similar problem. May be you are running user instances. Please add more details:
add information about your connection string (i am assuming your are using file attached connnections with a local data file)
where do you click on your database? Are you clicking on the mdf file or are you using management studio or visual studio
There is two major ways, you can use Entity Framework or ADO.NET foundation.
For simple tasks you can use ado.net features. at first you have to create SqlConnection Object and pass your ConnectionString to the constructor. Second you have to use SqlCommand Object and set your desired Command Text for the command. and at last you have to Execute the Command. there are several ways for execution :
ExecuteNonQuery For Updates, Deletes and Inserts commands
ExuecuteReader For Select commands, this methods returns a SqlDataReader which you can get your result from it.

How do I make a non absolute connection string so my small database works with my published C# application?

I'm working on a small project to track information. This C# application will take information uploaded via CSV/Excel and store/sort it.
My current connection string is an absolute path (off thumb drive). I'm worried that when I publish it, the database connection won't work on a random users computer.
<add name="PPP_Project.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Other PPP Projects\PPP_Project_Test\PPP_Project\Database1.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
How do I have this set so it will work when the application is published?
you can use this:
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Customers.mdf;Integrated Security=True;User Instance=True
as described here.
For a winform application, the default |DataDirectory| is the same where the application is installed. Of course you can use aa a part of a more nested path.
If you want to specifyng something else you can use the AppDomain.SetData method.
The easiest way to manipulate connection strings is with the ConnectionStringBuilder classes:
OleStringBuilder = new OleDbConnectionStringBuilder(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';");
OleStringBuilder.DataSource = MapPath(#"~\App_Datav\MyExcelWorksheet.xls");

How do I connect to an .mdf (Microsoft SQL Server Database File) in a simple web project?

Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.
A great resource I always keep around is connectionstrings.com.
It's really handy for finding these connection strings when you can't find an example.
Particularly this page applied to your problem
Attach a database file on connect to a local SQL Server Express instance
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
So here's the answer from MSDN:
Choos[e] "Add New Data Source" from the
Data menu.[And follow the connection wizard]
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
Click on Tools >> Connect to Database...
Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "AttachDbFilename" attribute and value. Example:
The raw text from the Advanced panel:
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
The actual entry in the web.config:
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
Just one more -- i've always kept a udl file on my desktop to easily create and test connection strings. If you've never done it before - create a new text file and name it to connection.udl (the ext is the only important part). Open the file, start on the Provider tab and work your way through. Once you're happy with the connection rename the file giving it a .txt extension. Open the file and copy the string - it's relatively easy and lets you test the connection before using it.
<add name="Your Database" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Expanse.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add
string constr = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=|DataDirectory|\myData.mdf; Integrated Security=True; Connect Timeout=30;";
using (SqlConnection conn = new SqlConnection(constr))
string constr = ConfigurationManager.ConnectionStrings["myData"].ToString();
using (SqlConnection conn = new SqlConnection(constr))
{
sqlQuery=" Your Query here"
SqlCommand com = new SqlCommand(sqlQuery, conn);
com.Connection.Open();
string strOutput = (string)com.ExecuteScalar();
}

Categories