I have a connection string in App.config like so:
<add name="connectionString"
connectionString="Data Source=SERVER;Initial Catalog=DB;Integrated Security=True;User ID=domain\username;Password=12345;Connection Timeout=300"
providerName="System.Data.SqlClient" />
I then call the string in code behind like so:
string conSTR = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlDataReader reader;
using (SqlConnection sqlConn = new SqlConnection(conSTR))
using (SqlCommand cmd = new SqlCommand(SQLQuery, sqlConn))
{
sqlConn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
.... stuff happens here
}
}
MY local account does not have access to the server but the service account passed into the connection string does.
The error I get is:
Cannot open database "DB" requested by the login. The login failed.
Login failed for user 'domain\MyUserName'.
For some reason it is completely ignoring the user name/password in the connection string and tries to connect using my account.
How can I fix that?
you have integrated security = true in your connection string, remove that.
That because you're specifying Integrated Security=True;. This overrules any other authentication settings, remove it and it will use the username and password supplied.
Related
I'm trying to connect to a database, but it seems like my connection is not going through. I am using C# MVC for the webpage I'm creating. How can I fix the following error:
System.ArgumentException: 'Keyword not supported: 'metadata'.'.
The error is occuring on the line using (Sqlconnection con = new Sqlconnection(conStr)). What am I doing wrong on this line and is this how you call your SQL query in C# MVC?
string conStr = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"].ConnectionString;
List<FisYear> YerFis = new List<FisYear>();
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand("select * from [dbo].[FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
FisYear fy = new FisYear();
fy.FisDate = rdr["ST_FI"].ToString();
YerFis.Add(fy);
}
SelectList list = new SelectList(YerFis, "ST_FI", "FisDate");
ViewBag.DropdownList = list;
}
You're almost certainly trying to use an entity framework connection string to open a connection via new SqlConnection, which won't work.
If you look in your web.config file you'll probably see something similar to:
<connectionStrings>
<add name="Training_DatabaseEntities" connectionString="metadata=res://*/Entity.csdl|res://*.............provider=System.Data.SqlClient;provider connection string=............." />
</connectionStrings>
You could try parsing the connection string by hand to retrieve the bit you actually want, a brief web search suggests that the EntityConnectionStringBuilder may be of use to retrieve it programmatically, here's an example of doing that in a console app:
var connectionString = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"]
.ConnectionString;
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionString);
var sqlConnectionConnectionString = entityConnectionStringBuilder.ProviderConnectionString;
Console.WriteLine($"EF Connection String: {connectionString}");
Console.WriteLine($"SqlConnection Connection String: {sqlConnectionConnectionString}");
This gives the output (my emphasis):
EF Connection String: metadata=res:///Models.Model1.csdl|res:///Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
SqlConnection Connection String: data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework
Which shows a connection string that can be passed into a SqlConnection instance.
I'm trying to connect to SQL Server 2014 using my C# code
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=IP\\SQLNameSERVER,1433;Network Library=DBMSSOCN; Initial Catalog=MyDB; User ID=Username; Password=password;"/>
</connectionStrings>
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
query = "SELECT * FROM [MyTable]";
using (SqlCommand commandUserPortal = new SqlCommand(query, cn))
{
cn.Open();
}
}
but I get an error message:
Login failed for user 'Username'.
When I use the same credentials to connect to DB through SQL Server Management Studio, it works fine without any issues.
The user has db_datareader permission.
I also tried
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=IP\\SQLNameSERVER,1433;Network Library=DBMSSOCN; Initial Catalog=MyDB; User ID=Username; Password=password;
providerName="System.Data.SqlClient"/>
</connectionStrings>
Use an accurate connection string via using Add connection from Visual studio.
How:-
Follow the next screen shots:-
1) View >> Server Explorer
2) Add Connection
3) Choose data source >> SQL Server
4) Type Server Name, SQL Server authentication , type username and password, and choose database.
5) Click Test Connection button.
6) The Connection that you created will be added here
7) Right click and choose properties
8) Finally copy and paste the connection string and use it , and replace the stars (********) with your password
Try to change setting in sql server for you database. Allow both sql and windows authentication. For steps with images, check here. I hope that you are not using windows authentication and also the DB server is reachable by your network. Everything else is looking ok to me.
Use the following as Connection String
<add name="DefaultConnection" connectionString="data source=192.168.0.1; initial catalog=DBNAME;persist security info=True;user id=UserId;password=Password;MultipleActiveResultSets=True ; Connect Timeout=10000" providerName="System.Data.SqlClient" />
Replace your Database name in the catalog,user id in user id and passeord in password
try to change your Connection String:
<add name="ConnectionString" connectionString="Data source=IP\SQLNameSERVER;Initial Catalog=DBname;User=Username;Password=Password; connection timeout=6000;" />
Also try to change your Code:
from:
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
query = "SELECT * FROM [MyTable]";
using (SqlCommand commandUserPortal = new SqlCommand(query, cn))
{
cn.Open();
}
}
to:
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
query = "SELECT * FROM [MyTable]";
cn.Open();
using (SqlCommand commandUserPortal = new SqlCommand(query, cn))
{
}
}
I am working with asp.net web services using c# need to access the database in web service but getting error in connection string can any one tell me how to specify the connections string of database here..
here is my code here I am using connection string as i use the string in web form..I am beginner so please guide me in step by step manner or reffer any clear and easily understandable manner as I could not get the point how connection sting is being specified in no of tutorials..
[WebMethod(Description = "show student data")]
public DataSet values(int a)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from STUDENT where stdID='"+a+"'", con);
SqlDataReader r;
r = cmd.ExecuteReader();
r.Read();
foreach
return r;
SqlDataAdapter ada = new SqlDataAdapter("Select * from STUDENT where stdID='" + a + "'", con);
DataSet ds = new DataSet();
ada.Fill(ds);
return ds;
}
Here your just to provide name of connection string in .ConnectionStrings[""] bracket and put your connection string in web.config file as per below.
<connectionStrings>
<add name="Dbconnection"
connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True" ;
providerName="System.Data.SqlClient" />
</connectionStrings>
add this connection string in configuration manager tag in web.config file and write following connection
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString);
add in comment if you need any more help.
Your connection string is a bit wrong... try something like
SqlConnection con = new SqlConnection(
"Data Source=.\\SQLEXPRESS;Initial Catalog=PUTYOURDATABASENAMEHERENOTTHEFILENAME;Integrated Security=True;User ID=YourUserID;Password=YourPassword");
"The User Instance feature is deprecated with SQL Server 2012, use the SQL Server Express LocalDB feature instead." https://www.connectionstrings.com/sql-server/
Very new to C# and VS2012.
I'm trying to connect to a local database connection.
Here is the code
string selectSql = "select * from Tasks";
string connectionString = "Data Source=adamssqlserver;database=master;Integrated Security=true;";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(selectSql, cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
//do something
}
}
Here is the error
Keyword not supported: 'database'.
If I put in Initial Catalog first
"Data Source=adamssqlserver;Initial Catalog=etc;"
Then the error gives the same message but for "Initial Catalog".
Here is my data connection
You are using SqlCeConnection not a SqlConnection
This class (SqlCeConnection) is for Sql Compact Edition where the syntax rules of the connection string are different. For example:
Data Source=MyData.sdf;Persist Security Info=False;
Instead your connection string is for a Sql Server or Sql Server Express.
So, if your target database is a SqlServer db as your tag indicates then you need to use
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(selectSql, cn))
{
....
}
Instead of Data Source, try Server, e.g:
string connectionString = "Server=adamssqlserver;Database=master";
This website contains good information for setting up connection string. There are so many options I usually have to turn to a reference to get it set up correctly.
Just a reminder: when using MS Access databases, you need to use OleDbConnection and OleDbCommand, not SqlConnection and SqlCommand. 'Provider' in the connection string for SqlConnection is invalid AFAIK.
Are you missing the " from the connection string section.
Should be
<add name="StevenTestEntities"
connectionString="metadata=res://*/Model.TestModel.csdl|res://*/Model.TestModel.ssdl|res://*/Model.TestModel.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=Data Source=D000097;
Initial Catalog=StevenTest;
Integrated Security=True;MultipleActiveResultSets=True&qout;"
providerName="System.Data.EntityClient" />
Try that out.
I am currently trying to establish a connection between an ASP.NET web site project and a Database built by SQL Server 2008 R2.
The way I am required to do so is to use the connectionString from the Web.config page, but I have no idea what value to give it or how to establish a connection using said value. (Using C#)
Any help would be appreciated, as I found next to no information about the subject.
Here is the (default) value that is currently in the Web.config page:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Use Configuration Manager:
using System.Data.SqlClient;
using System.Configuration;
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using(SqlConnection SqlConnection = new SqlConnection(connectionString));
//The rest is here to show you how this connection would be used. But the code above this comment is all you really asked for, which is how to connect.
{
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
SqlCommand SqlCommand = new SqlCommand();
SqlConnection.Open();
SqlCommand.CommandText = "select * from table";
SqlCommand.Connection = SqlConnection;
SqlDataReader dr = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
This article about Connect to SQL Server Using SQL Authentication in ASP.NET will probably give you a better idea of what need to be done.
As a pre check, just check if your mssqlserver services are running.
string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
// command.Parameters.AddWithValue("#param", value);
connection.Open();
command.ExecuteNonQuery(); // or command.ExecuteScalar() or command.ExecuteRader()
}