I am trying to connect to a SQL Server database in my website. I have created a database from Add -> Add New Item -> SQL Server database. The name of my database file is database.mdf.
I have created a ConnectionString:
<connectionStrings>
<add name="Khulna_website"
connectionString= "Server=(localDB)\\v11.0;Integrated Security=SSPI;Database=Database.mdf;"
providerName="System.Data.SqlClient" />
</connectionStrings>
My first question is, when I open a database that way, is it necessary to add a connection string? Asking that because I can already see a green connection line on the side of the database.
Then, how do I connect it on my C# code?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
The question is, what do I add on ["RegistrationConnectionString"] part? Should I give the name of my ConnectionString? Am I missing any point here? I am completely new here. Any help would be highly appreciated.
Yes, in order to connect to a database - you do need some form of a connection string - one way or another. It's typically considered a best practice to put those connection strings into a config file, so you can modify it without changing your code.
To retrieve the actual connection string from the config, you need to use the name=.... to you gave it in the config file:
<add name="Khulna_website"
*************** this is the **name** of your connection string
Retrieve it like this:
string conStr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
************** same name again
and then use it to create your connection object to the database:
SqlConnection conn = new SqlConnection(conStr);
Put the name of the connection string which is Khulna_website instead of RegistrationConnectionString
So I'm using a connection string from my app.config file to connect to my database. I also tried to make it more secure, so that my SqlCOnnectionStringBuilder retrieves its info from the app.config file. To give you a better idea of what I mean here's some code:
app.config:
<connectionStrings>
<clear/>
<add name="connection"
connectionString="Data Source=SERVERIP; Initial Catalog=DB;
Port=3306; User ID=USERNAME; Password=PASSWORD;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Method for the connection builder:
private void BuildConnectionString()
{
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["connection"];
if (null != settings)
{
MySqlConnectionStringBuilder builder =
new MySqlConnectionStringBuilder(settings.ConnectionString);
conString = builder.ConnectionString;
}
}
Somehow the user id gets replaced with the name of my computer, which is very wierd since the IP, port and the initial catalog aren't being replaced.
Oh and I followed this handy article here on MSDN.
Can someone please tell me what I'm doing wrong here?
EDIT:
Here is the full error I'm getting:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Host 'nameofpc' is not allowed to connect to this MariaDB server
It seems to me that the problem is that the MariaDB server is only accepting incoming connections from a certain set of hosts. Most likely the server is defaulted to accept only localhost connections. I think that this link might be helpful: https://mariadb.com/kb/en/mariadb/configuring-mariadb-for-remote-client-access/.
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 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/
This line:
WebSecurity.InitializeDatabaseConnection(connectionStringName: "DefaultConnection", userTableName: "UserProfile", userIdColumn: "UserID", userNameColumn: "UserName", autoCreateTables: true);
Is throwing:
'System.ArgumentException' occurred in System.Data.dll but was not handled in user code
Additional information: Keyword not supported: 'metadata'.
My connection string is:
add name="DefaultConnection" connectionString="metadata=res://*/TalyllynModel.csdl|res://*/TalyllynModel.ssdl|res://*/TalyllynModel.msl;provider=System.Data.SqlClient;provider connection string="data source=***********;initial catalog=********;persist security info=True;user id=*********;password=********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.SqlClient" /></connectionStrings>
Not sure where it is im going wrong.
The string you passed is not a valid database connection string, it's an EF connection string that contains a SQL Server connection string in its provider connection string parameter. WebSecurity.InitializeDatabaseConnection expects a valid database connection string
To avoid parsing the connection string yourself, you can use the EntityConnectionStringBuilder class to parse the string and retrieve the database connection string from its ProviderConnectionString property
When this happened to me it was because the connection string had:
providerName="System.Data.SqlClient"
but it should be:
providerName="System.Data.EntityClient"
because as was said by the other answer, it is an EF connection string.
Just to add another possibility (which I encountered) - which might be the case if you're developing/maintaining an Azure WebApp, using a connection string saved in Azure's Application Settings.
Beside each connection string in the Application Settings is a dropdown for the connection string type - it's very easy to forget to set this to 'Custom' for Entity Framework values and leave it at the default (SQL Database) - which also causes the above error.
Here's some code I use, to extract the database name & server name from a connection string.
Notice how it checks if it's an Entity Framework connection string, and if so, it extracts the "provider connection string" part of that, which can then be passed into SqlConnectionStringBuilder:
If I didn't do this, I'd get that nasty "Keyword Not Supported: Metadata" error.
if (connectionString.ToLower().StartsWith("metadata="))
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(connectionString);
connectionString = efBuilder.ProviderConnectionString;
}
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
DatabaseServer = builder.DataSource; // eg "MikesServer"
DatabaseName = builder.InitialCatalog; // eg "Northwind"
I'm going to throw out another answer, just in case someone else runs into this through the same weird scenario as I did.
To start with, as others have said, ADO connection strings and EF connection strings are different.
An ADO connection string contains a number of semicolon-separated fields, which can very from one connection type to another, but you usually see "data source=xxx", "initial catalog=yyy", etc. You will not see "metadata=zzz".
An EF connection string has the same structure, but it has a "metadata=zzz" and a "provider connection string=www", where "www" is an escaped ADO connection string.
So a normal format for an ADO connection string is:
data source=myserver;
initial catalog=mydatabase;
Persist Security Info=True;
User ID=myusername;
Password=mypassword;
MultipleActiveResultSets=True
While a normal format for an EF connection string is:
metadata=res://*/MyDbContext.csdl|
res://*/MyDbContext.ssdl|
res://*/MyDbContext.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=myserver;
initial catalog=mydatabase;
Persist Security Info=True;
User ID=myusername;
Password=mypassword;
MultipleActiveResultSets=True;
application name=EntityFramework
"
Most folks who are running into this problem seem to have cut an EF connection string and pasted it into a place that needed an ADO connection string. In essence, I did the same thing, but the process wasn't as clear as all that.
In my case, I had a web application that used EF, so its web.config properly contained EF connection strings.
I published a deployment package, and the process prompts you for the connection strings to be used when deploying. These are stored in the deployment package's generated SetParameters.xml file.
I cut and pasted the EF connection strings into the publish dialog's entry fields.
I deployed the web application, tried to access it, and got the "Keyword not supported: metadata" error.
What I didn't realize is that MS's publish tool expected an ADO connection string, and that given it it would construct an EF connection string.
The result was that SetParameters.xml and my deployed web.config had connection strings that looked like this:
metadata=res://*/MyDbContext.csdl|
res://*/MyDbContext.ssdl|
res://*/MyDbContext.msl;
provider=System.Data.SqlClient;
provider connection string="
metadata=res://*/XxDbContext.csdl|
res://*/XxDbContext.ssdl|
res://*/XxDbContext.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=myserver;
initial catalog=mydatabase;
Persist Security Info=True;
User ID=myusername;
Password=mypassword;
MultipleActiveResultSets=True;
application name=EntityFramework
"
""
In other words, the embedded provider connection string was an EF connection string and not an ADO connection string, so when EF tried to use it to connect to the database, it generated this error.
In other words, when you are pasting the connection strings into the publish dialogues, you need to paste a ADO connection string, not an EF connection string, even if what you have in the web.config you are copying from is an EF connection string.
You can extract an ADO connection string from the provider connection string field of an EF connection string, and that's what you will need, if you're using the same connection in the deploy as you did in local development.
For use in Azure Application Settings => Connection Strings:
If the connection string is generated by EF-designer be sure to replace &qout; with " in the string.
Check that provider=System.Data.SqlClient
Choose Type Custom in the dropdown
If the connection is for a model (Entity Framework) ensure that correct path to your model is used
Ex: A model "MyWebRoot/Models/MyModel.edmx" is configured as: metadata=res:///Models.MyModel.csdl|res:///Models.MyModel.ssdl|res://*/Models.MyModel.msl;
Hi,
In my opinion, the connection string for ADO.NET (in this
caseSqlConnection) can't use 'metadata. You're using the one specific
for Entity Framework. The ADO.NET one should be something like:
"data source=KAPS-PC\KAPSSERVER;initial catalog=vibrant;integrated security=True"
So, to sum it up, you need two separate connection strings, one for EF
and one for ADO.NET.
Souce: http://forums.iis.net/post/2097280.aspx
For Azure Web App, Connection string type has not "System.Data.EntityClient", Custom works good.
Dry This,
Remove metadata Info from your ConnectionString.
Change this.
<add name="DefaultConnection" connectionString="metadata=res://*/TalyllynModel.csdl|res://*/TalyllynModel.ssdl|res://*/TalyllynModel.msl;provider=System.Data.SqlClient;provider connection string="data source=***********;initial catalog=********;persist security info=True;user id=*********;password=********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.SqlClient" /></connectionStrings>
To
<add name="DefaultConnection" connectionString="data source=***********;initial catalog=********;persist security info=True;user id=*********;password=********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.SqlClient" /></connectionStrings>
Before i give My Solution let me explain something , I got this problem too , im using EntityFramework and Ado.net you cant use Entity framework Connection string in ADo and vice versa , so what i did was in the Web.config file i left the EF Connection string(Metadata one)
and in the Controller for ADO i Added the connection string which i got from the database(properties). add the ADO string like this :
SqlConnection sql = new SqlConnection();
sql.ConnectionString = #"Data Source=.\alienbwr;Initial Catalog=ABTO_POS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";(dont use my string)
An old post but my solution,
Unfortunately these didn't solve it for me using Azure Functions talking to a separate project (class library) with an EDMX.
I had to edit the Context.CS class constructor replacing the
: base ("Entities")
with
: base (ConfigurationManager.ConnectionStrings["Entities"].ConnectionString)
Hopefully this might help someone else in need.
Check in this place
<add name="ConnectionString" connectionString="Data Source=SMITH;Initial Catalog=db_ISMT;Persist Security Info=True;User ID=sa;Password=#darksoul45;MultipleActiveResultSets=True;Application Name=EntityFramework"
providerName="System.Data.SqlClient" />
As you can see there's a two connection string one for ADO and another for the Login System or whatever you want. In my case, ConnectionString is for Login system so I've used that in:-
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = null;
SqlDataReader dr = null;
protected void Page_Load(object sender, EventArgs e)