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
Related
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]
i am trying to bind data to Gridview and getting this error
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: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
this is my simple code
string cs = "data source =.; initial catalog= MyDB; integrated security= SSPI";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from tbl_Dept", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
in SQl management studio i have rechecked db name and its same as mentioned in code
I found some related questions but those did not work for me so posting mine one , Please help me with it,
You can define SqlConnection string in your web.config(in web applications) or app.config(in windows form application).
Simply define like this -
<configuration>
<connectionStrings>
<add name="Connection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DBName;Trusted_connection=yes;User ID=''; Password=''"/
</connectionStrings>
</configuration>
then access this code in you .cs form using
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString.ToString());
and after this you can use SqlConnection object con in you whole form.
When you install SQL Server Express the setup propose to create a named instance, and by default, this named instance, is called SQLEXPRESS.
When you want to connect to this named instance it is required to specify the name.
So, in your case your connection string should be changed to
"Data Source =.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI";
I am trying to make a database application. I added local database from
add > new item > local database.sdf
In Server Explorer, I created a table in the database. But I am having trouble connecting to it.
I want to show all the data in a DataGrid.
My code:
string ConnectionString = #"Data Source=""c:\users\asus\documents\visual studio 2012\Projects\WpfApplicationLocalDB\WpfApplicationLocalDB\LocalDB.sdf""";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
List<DataRow> lis = dt.AsEnumerable().ToList();
DataGridView.ItemsSource = lis;
But when I build it, Visual Studio finds conn.open(); error. A message says that
SqlException was unhandled by user
Please help...
Also, can anyone suggest a tutorial of how can I create a simple database application in C#? Please help.
If you're using a .sdf file, you're using Microsoft SQL Server Compact Edition (SQL Server CE).
When using SQL Server CE, you must use SqlCeConnection and SqlCeCommand classes - not SqlConnection and SqlCommand (those are for the "full", server-based versions of SQL Server)
I want to detach the database from SQL Server 2005 from my C# code. I use the DROP query to detach. But it statements delete the file from my local system. I want to detach the database and copy that database in runtime.
First try to connect to the SQL Server without providing any database name,or path just like below:
ConnectionString = #"Data Source= YourDataSource ;Integrated Security=True;Connect Timeout=30";
Note:
YourDataSource can either be . or .\SQLEXPRESS or .\MSSQLSERVER or (local)\SQLEXPRESS or (localdb)\v11.0 or etc.
Then by using the following query, detach your database.
"ALTER DATABASE [your DB] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [your DB]";
Ok.
My Sample code:
sql_connect1.ConnectionString = #"Data Source=.\sqlexpress;Integrated Security=True;Connect Timeout=30";
sql_command.CommandText = "ALTER DATABASE [IRAN] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [IRAN]";
sql_command.Connection = sql_connect1;
sql_connect1.Open();
sql_command.ExecuteNonQuery();
sql_connect1.Close();
The SQL Server SMO API let's you do anything Sql Server management studio can do (from c# code).
Check out this link
http://msdn.microsoft.com/en-us/library/ms162175.aspx
you can detach a database on SqlServer by the following code:
There is a stored procedure in SqlServedr 'sp_detach_db' for detach a database, has one argument DataBaseName. Here in the code 'MyDatabase' is the database name you should change it with your database name
// C# Code
SqlConnection conn = new SqlConnection("Server=(local); Data Source=;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("", conn);
cmd.CommandText = "sys.sp_detach_db MyDatabase";
conn.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();
You can use stored procedures for your problem. following link can be useful:
http://msdn.microsoft.com/en-us/library/aa259611.aspx
Myo Thu's comments lead me in the right direction, so here's a summary of steps on how to detach the database.
Step 1: Reference the following DLL's in your project [Reference]:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
Step 2: using:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
Step 3: Code
var server = new Server(new ServerConnection(#"MyMachine\SQL2012"));
// Ensure database is not in use
server.KillAllProcesses("TestDatabase");
server.DetachDatabase("TestDatabase", true);
EDIT: Now documented in my blog here
every one. I want to connect a remote database using Sql Connection String in C#.net, I am trying it to do, but failed to connect. I am new to C#.net connections to the Database. Can any one pls tell me how to write the Connection String.
Check this website for the specific format: http://www.connectionstrings.com/
Here is a little bit of code that will connect to a dabase called myDatabase on a server called myServer, query the myTable table for the column myColumn, and insert the returned data into a list of strings.
While by no means exaustive or perfect, this snippet does show some of the core aspects of working with data in C#.
List<string> results = new List<string>();
SqlConnection conn = new SqlConnection("Data Source = myServerAddress; Initial Catalog = myDataBase; User Id = myUsername; Password = myPassword;");
using (SqlCommand command = new SqlCommand())
{
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "Select myColumn from myTable";
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
results.Add(dr["myColumn"].ToString());
}
}
}
There is no difference in this regard. The connection string to connect to remote server database is written same as you write to connect to local database server.
However, only Data Source changes.
Below is a sample connection string
User ID=dbUserName;Password=dbUserPwd;Initial Catalog=dbName;Data Source=remoteMachine\serverInstanceNameIfAny;
But by default sql server is not configured to Sql Server Authentication, so you need to enable
Sql server authentication
Also Create a Log in user in the database
Here are a couple of examples:
With Integrated Security
Server=RemoteMachineName\Intance; Initial Catalog=DatabaseName; Integrated Security=true;
With username and password
Server=RemoteMachineName\Intance; Initial Catalog=DatabaseName; UID=Username; PWD=Password;
You can also do that in web.config file
<configuration>
<ConnectionStrings>
<add name="YourConnectionString" connectionString="Data Source=Nameofserver;
InitialCatalog=NameofDatabase;Persist Security Info=True;
UserID=DatabaseUserID;Password=DatabasePassword" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>