Connect a .mdf database to a C# form - c#

I have a .mdf database called Persons in my project in Visual Studio 2012. And have a Windows forms application.
I have a button on the form called addToDb. When clicking it, I want to add something to the database.
This is my code:
SqlConnection myDbConnection = new SqlConnection ()
myDbConnection.SqlString = "Addr=Persons.mdf;"
I don't know the connection string and I find it in the net but it makes for me an error and doesn't open the database connection when I use:
myDbConnection.open();
error 40 - Could not open a connection to SQL Server

You should refer to www.connectionstrings.com if you do not know the correct connectionstring.
If you use SqlExpress, which I conclude from you .mdf file the syntax would be
string connectionString =#"Data Source=.\SQLEXPRESS; AttachDbFilename=c:\path\tofile.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";
using(SqlConnection myDbconnection = new SqlConnection(connectionString)
{
myDbConnection.Open();
//DoStuff
}

Related

Trying to connect to SQL Server using C#

I am trying to connect to SQL Server and get data. This is what I did, but it's not working:
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=(IP)\PC-NAME\SQLEXPRESS,3306;Network Library=DBMSSOCN;Initial Catalog=dbase;User ID=sa;Password=password";
cnn = new SqlConnection(connectionString);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
Your Code is Correct, except your connection string i think
So, first, connect to your database via server Explorer in VisualStudio\View menu
Then right-click on your database and select properties and check the connection string and copy that for test
I think you have a problem with your connection string.
Check your connection string using this given example:
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial
Catalog=myDataBase;User ID=myUsername;Password=myPassword;

How to automatically attach SQL Server database in C#?

I am new to C# and SQL Server 2014 Express and I am using Windows forms.
I am building the small application which read/write from/to SQL Server database.
I am trying to automatically attach SQL Server database, then read data from a table named Test_Table and then fill a Datagridview.
The code I used:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand= new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter= new SqlDataAdapter();
private void button1_Click(object sender, EventArgs e)
{
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM Test_Table ";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
dataGridView1.DataSource = DataTable;
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
App.config:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=localhost; AttachDbFilename=D:\\DB\\MyDB.mdf;Integrated Security=True"/>
</connectionStrings>
When I click on button1 it throws an error:
An attempt to attach an auto-named database for file D:\DB\MyDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have no other databases attached and the database path is correct.
I had a look here, here and here but non of them helped.
Any idea how can I automatically attach a SQL Server database file? Thank you
What is the version of SQL Server are you using? This will explain a lot about your error message.
Your Connection String:
"Data Source=localhost; AttachDbFilename=D:\DB\MyDB.mdf;Integrated
Security=True"
You can only use AttachDbFilename with SQL Express. In your connection string, the Data Source is set to localhost. That sounds like you have a full version SQL Server installed.
If you have a full version of SQL Server installed, you can only attach a database via Management Studio.
If you are using SQL Express, change your data source:
Data Source=.\SQLEXPRESS

Getting my sql database to work with my hit counter code in asp.net

I been trying to follow this tutorial to create a hit counter for my website using asp.net/c# and html/css. I'm running this off localhost. I'm having trouble configuring or getting the sql database connectionstring to work. Here is a link to the tutorial I'm using Hit counter in asp.net. So I follow the tutorial and run the code, and i get this error
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I'm pretty sure it has to do with how i wrote the ConnectionString in the web Config file. Maybe I'm pointing the data source to the wrong place? Maybe it's because i'm not using Initial Catalog in the connection string?
connectionstring in my web config file:
<connectionStrings>
<add name="ConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;
Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
calling my connectionstring from .cs file
/objects we will need to work with the db
SqlConnection conn;
SqlCommand cmd;
//IF PAGE IS NOT A POSTBACK, ADD A HIT
if (!Page.IsPostBack)
{
//connect to the db
conn = new
SqlConnection(WebConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString);
//the sql command to increment hits by 1
cmd = new SqlCommand("UPDATE Hits SET Hits = Hits+1 WHERE
Name=#Name", conn);
cmd.CommandType = CommandType.Text;
//update where Name is 'About' which corresponds to this page
cmd.Parameters.AddWithValue("#Name", "About");
using (conn)
{
//open the connection
conn.Open();
//send the query
cmd.ExecuteNonQuery();
}
I'm still a newbie when it comes to all this database stuff, any help be appreciated.
update fixed: I followed the instructions by user1551066 and found my data source for the database.mdf and then i plugged it in my connectionstring in web config and it WORKED.
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=
(LocalDB)\v11.0;AttachDbFilename=C:\Users\bobdole\Desktop
\VideoWebsite\VideoWebsite\VideoWebsite\App_Data\Database.mdf;
Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Try to connect to your .mdf database in visual studio. 1)Go to server explorer tab. 2)You should see your database .mdf file (possibly as DefaultConnection) 3) Click on it. In the Properties window you wil see the section Connection. Unfold it and you will see the ConnectionString property. Copy and paste it in your web.config ConnectionString setting.
Your error is due to SQL connection failure.Please check the connection string which you have passed was correct.For connection string reference please refer here.
Sql Server connection string
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
If you have a named instance of SQL Server, you'll need to add that as well.
"Server=localhost\sqlexpress"
and for connecting SQL Server
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Please refer [here][2]

Error establishing connection to SQL Server

I just started creating a local database in Visual Studio for the first time and I'm having a hard time making it work.
In modify connection I tested and it works and also got the connection string:
string ConnectionString = #"Data Source=D:\Bratulescu Mihai\WindowsFormsApplication1\WindowsFormsApplication1\NodeBDatabase.sdf";
sqlConn = new SqlConnection(ConnectionString);
sqlConn.Open();
But when it tries Open() it cannot connect. I don't know much about this whole server thing, I just created the db and it's DataSet.
If you are using SQLCe since I see you are reffering to an sdf file you should add a reference of System.Data.SqlServerCe and try:
using System.Data.SqlServerCe;
....
sqlConn = new SqlCeConnection(ConnectionString);
sqlConn.Open();
are you sure about the connection string?
You could take a look at this site: http://www.connectionstrings.com/sql-server-compact/

Connection String Problem

I am a programmer trying to teach myself C#. I am trying to connect the the Northwind.mdf database in a form. I have used the Database Explorer to attach the database to the form, and the test connection button worked. For the connection string I am using "server=.\\sqlexpress; Trusted_Connection=yes; database=Northwind" This connection fails in SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommand, connectionString); Google has been no help. Any ideas?
Try this?
Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;
Right click on the connection in the "Database Explorer".
Click on "Properties".
See the "Connection String" in the properties window, with its value on the right.
Is this the same connection string, as the one you posted?
Here is the connection string, I could see with a new mdf file I created
Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kalpesh\Documents\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True
Assuming that the connection string is correct, you will have to escape it in c# (if it contains any of the characters that requires it. for e.g. the backslash character)
string connectionstring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kalpesh\Documents\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
In your case, it should be the path to the Northwind.mdf located on your machine.
Does this work?

Categories

Resources