How do I connect to an MDF database file? - c#

I'm experimenting in connecting a C# app to an MDF database for the first time, and I need a little help ..
I made a small MDF database file in Visual Studio 2010, then created another project and imported the file into the project itself.
I am not trying to connect to the MDF file via code. Here the code I'm using:
namespace DBtestApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
System.Data.SqlClient.SqlConnection con;
private void Form1_Load(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "DataSource=.\\SQLEXPRESS; AttachDbFilename =SampleDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
MessageBox.Show("Connection opened");
con.Close();
MessageBox.Show("Connection closed");
}
}
}
When I run the application, I get an exception at the line where I define the connection string, and the exception has this message at the top of the stack:
System.ArgumentException: Keyword not supported: 'datasource'.
Can someone point me in the right direction ?

Add space between Data Source
con.ConnectionString = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=c:\folder\SampleDatabase.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";

Go to server explorer > Your Database > Right Click > properties > ConnectionString and copy the connection string and past the copied to connectiongstring code :)

string sqlCon = #"Data Source=.\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\SampleDB.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
SqlConnection Con = new SqlConnection(sqlCon);
The filepath should have |DataDirectory| which actually links to "current project directory\App_Data\" or "current project directory" and get the .mdf file.....Place the .mdf in either of these places and should work in visual studio 2010.And when you use the standalone application on production system, then the current path where the executable file is, should have the .mdf file.

For Visual Studio 2015 the connection string is:
"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True"

Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;

Alternative solution, where you can have the database in the folder you want inside the solution. That worked for me:
.ConnectionString(#"Data Source=(LocalDB)\MSSQLLocalDB;
AttachDbFilename="+AppDomain.CurrentDomain.BaseDirectory+"Folder1\\Folder2\\SampleDatabase.mdf" + ";
Integrated Security=True;")

SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Samples\MyApp\C#\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
this is working for me... Is there any way to short the path? like
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\hasif\Documents\Visual Studio 2015\Projects\vgsoft\SqlserverRepo\data\Database1.mdf";Integrated Security=True;Connect Timeout=30
1
2
ConnectionString

Related

Trying to make an SQL connection with local database .mdf but I succeed to write the filename directory

I have this line for the connection with my connection string
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=""C: \Users\BDV\Documents\Visual Studio 2015\Projects\Interface_notes\Interface_notes\Database1.mdf"";Integrated Security=True;Connect Timeout=30");
But I get this error :
Class System.String
Represents Text as a series of Unicode characters
Syntax Error, ',' expected
I think the problem is with the double quotation marks, but I can't figure out what I can do instead. Can someone help me with this? Thanks
Unrecognized escape sequence
There are two errors in your connection string. One has been already explained to you. This is C# and you need to prefix your string with the verbatim character to avoid parsing error when your string contains a backslash. Also you should remove the double quote around your path. They are not needed here.
The second error is the missing backslash between the (LocalDB) and the instance name.
So you write
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;
AttachDbFilename=C:\Users\BDV\Documents\Visual Studio 2015\Project\Interface_notes\
Interface_notes\Database1.mdf;
Integrated Security=True;Connect Timeout=30");
You can use verbatim string and remove double quote from inside :
Change it to
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)MSSQLLocalDB;
AttachDbFilename=C:\Users\BDV\Documents\Visual Studio 2015\Project\Interface_notes\
Interface_notes\Database1.mdf;
Integrated Security=True;Connect Timeout=30");
Should be like
SqlConnection conn = new SqlConnection(#"Data Source=
(LocalDB)MSSQLLocalDB;AttachDbFilename=C:\Users\BDV\Documents\Visual Studio
2015\Projects\Interface_notes\Interface_notes\Database1.mdf;Integrated
Security=True;Connect Timeout=30");

Microsoft Visual Studio SQL server connection - invalid pointer

So, I want to create a SQL database in Microsoft SQL Management Studio and connect it to Microsoft Visual Studio. I linked the database to Visual Studio and it worked. Now, I want to open that connection to test it with a button on a windows form application. Every time I try, it says "invalid pointer" but the database name is correct. I don't know what is wrong.
I still get the invalid pointer error...My instance name is DESKTOP-BJSAO6B but it doesnt seem to work...
You need provide a proper connection string like
string connectionString =
"data source=.\SQLEXPRESS;initial catalog=student;integrated security=True;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
MessageBox.Show("You are connected");
}
where SQLEXPRESS - name your MSSQL instance ( may be different). More you can see here
For Ex:
string connectionString = "Data Source=Server-Name; Initial Catalog= Database-Name;Integrated Security=True"; //If you are using a local Database.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
MessageBox.Show("You are connected");

How to connect to local database and update a dataset in C#?

I have stored some products (a product contains: unique id - primary key, name, price, quantity) in a local database file (Stock.mdf, table for the products is called 'table').
The file is in my project folder in Visual Studio. When someone call an action in the form (WPF), a entry should be updated (new quantity).
In my C# code file i use the following code to connect to the database:
System.Data.SqlClient.SqlConnection con;
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Stock.mdf; |
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
//Do i need the connect timeout? Found it somewhere in the web
I know that I can update the table in SQL with this command:
UPDATE table
SET Quantity=newQuantity
WHERE Id=GivenId;
How can I connect to the local dataset and update a product with the new quantity in c#?
First of all, please make use of using statements. They will ensure that IDisposable.Dispose() is called.
Written from memory:
string cs = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Stock.mdf; |
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand("UPDATE table SET Quantity=#q WHERE Id=#Id", con))
{
cmd.Parameters.AddWithValue("#q", newQuanity);
cmd.Parameters.AddWithValue("#Id", GivenId);
con.Open();
cmd.ExecuteNonQuery();
}
Do i need the connect timeout? Found it somewhere in the web
The default is fine for most circumstances.
Note that it is better practice to place the connection string in your app.config (or web.config, for web apps).
<connectionStrings>
<add name="MyConnectionName" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Stock.mdf; |
Integrated Security=True;
Connect Timeout=30;
User Instance=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then access it like:
string cs =
ConfigurationManager.ConnectionStrings["MyConnectionName"].ConnectionString;
To connect to the Sql database using C# in Microsoft Visual studio,you have to manually add the System.Data.SqlSeverCe.dll name reference as follow:
Right-click on your Project >>> Add Reference
Browse >>> C:\Program Files\Microsoft SQL server Compact edition\v3.5\Desktop
Load >>> the System.Data.SqlSeverCe.dll >>> Add

How to backup from .mdf database that I created

I created a .mdf database file with Visual Studio 2008. I can retrieve and insert data into database but when I want to backup I receive an error.
My code:
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|C:\test\Data|\DB.mdf;Integrated Security=True;User Instance=True";
connect = new SqlConnection(con);
connect.Open();
SqlCommand command = new SqlCommand(#"backup database [" + System.Windows.Forms.Application.StartupPath + "\\Data\\DB.mdf] to disk ='"+str+"' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
The error is:
error : invalid value for key 'attachdbfilename'.
Seems like your connection string is incorrect.
Try this one:
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\test\Data\DB.mdf;Integrated Security=True;User Instance=True";
For more options, have a look at: http://www.connectionstrings.com/sql-server-2005
This is for SQL Server 2012 and .NET 4.0.1 only.
If you have those, you should be able to use AttachDbFilename.
Anyway, if you have an .MDF for embedded database and the instance is not running, you can just copy .MDF and .LDF to back up.
just use your connection string as
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["<your connection string name from your app.config file>"].ConnectionString);
i tried it and it worked for me.

Connecting to local SQL Server database using C#

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
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
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/
SqlConnection c = new SqlConnection(#"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
You try with this string connection
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.
Hope that helps.
Visual Studio 2019 (and probably a few previous versions).
View -> SQL Server Object Explorer
Top of the tree is 'SQL Server'
Under 'SQL Server', are couple of '(localdb)....'
Expand the (localdb)... -> Databases until you find your db.
Database Name (eg. Database1) -> Right-click -> Properties, and scroll the many properties (eg. "ANSI
NULL Default"). Find the "Connection string" property, copy the value
into your code, and you're running.

Categories