sql local database connection - c#

I am trying to open my local database in c# with this code :
SqlConnection c = new SqlConnection("Server = (LocalDB)\\v11.0 ;Integrated Security=True;Database =Informati;");
c.Open();
But i receive an error when he is trying to open it :
Cannot open database "Informati" requested by the login. The login failed.
Login failed for user 'AURELIAN121\Aurelian'.
I've tried to connect using
new SqlConnection("Server = (LocalDB)\v11.0 ;User id=AURELIAN121\Aurelian;Integrated Security=True;Database =Informati;");
but the error persist.

Your connection string is not correct :
For local database u can use dot also, like
SqlConnection c = new SqlConnection("Data Source=.;
Integrated Security=True;Initial Catalog=Informati;");
From error it seams that your local user does not have access permission on Sql server. U have to add create login first :http://www.reliasoft.com/support/rs40024.htm

This is works for me
1. Data Source=(LocalDb)\v11.0;Initial Catalog=CSN;Integrated Security=SSPI;
The full version
2. <add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog={catalog name};
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\{database name}.mdf"
providerName="System.Data.SqlClient" />;
where {catalog name} is your database name and {database name} also your database name
Here you can find full list of connection strings
http://www.connectionstrings.com/sql-server-2012/

Related

Database property not set in EntityConnection

I am attempting to create a new connection with the following code:
using (EntityConnection conn = new EntityConnection("name=SampleEntities"))
{
conn.Open();
}
I get the following error:
The underlying provider failed on Open.
It appears this is not working because the Database property of the EntityConnection class is not being set, but the Initial Catalog is set in the named connection in the app.config.
The connection string is the following:
<connectionStrings>
<add name="SampleEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=PROGRAMMINGEFDB1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
This matches what is in the EntityConnection.StoredConnection property. This string will set the source correctly in the EntityConnection but not the database.
I created a new project to see if that would help. When I went to create a new ADO Data Model, I realized I could not make a connection to the database, which is why the connection was not working. It turns out SQL Server service refused to start. I managed to fix this problem with this answer: SQL Server 2012 can't start because of a login failure

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]

ADO.NET : Error occurred while establishing a connection to SQL Server

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";

How to connect to the Remote Database using Connection String in C#.net

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>

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