Using connection string from web.config - c#

I try to connect to my database and I can do that using following code:
using (SqlConnection conn =
new SqlConnection("Data Source=.\\SQLEXPRESS; Initial Catalog=DocumentManager; Persist Security Info=True; Integrated Security=True"))
{ ... }
But, when I try this:
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString)) { ... }
it doesn't work anymore. My Connection String looks like this:
<add name="DatabaseConnection" connectionString="Data Source=.\\SQLEXPRESS; Initial Catalog=DocumentManager; Persist Security Info=True; Integrated Security=True" />
And, I can read the connectionString variable and it looks exactly like the string in the first case.

Your in-code connection string has an escaped "\" in it.
Try changing your web.config to:
<add name="DatabaseConnection" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=DocumentManager; Persist Security Info=True; Integrated Security=True" />
The "\" does not need to be escaped in your web.config.
This is an example of escaping the backslash.

Try this
string connectionString = System.Configuration.ConfigurationManager.AppSettings("DatabaseConnection");

Related

What is wrong in the following connection string?

I am trying to create page in asp.net page and I am getting the following error
Error:-System.NullReferenceException: Object reference not set to an instance of an object. at TestdateAssistor.user_info.Button1_Click1(Object sender, EventArgs e)
at this line
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
This is my complete code
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (#name,#add,#mob,#adhar,#dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("#name",TextBox1.Text);
com.Parameters.AddWithValue("#add",TextBox2.Text);
com.Parameters.AddWithValue("#mob",TextBox3.Text);
com.Parameters.AddWithValue("#adhar", TextBox4.Text);
com.Parameters.AddWithValue("#dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
What changes should I make in the connection string?
You’re using the connection string as a key to your connection strings defined in the Web.config. So you need to define the connection string there and give it a name, then reference it in the code by name:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
Code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
The ConnectionStrings is a collection automatically built for you by the framework. Its content is retrieved from the web.config where you should have it defined in the proper section.
Then you retrieve its value passing the Name between the square brackets not the whole connectionstring.
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
and in your web.config you add the proper definition for your connectionstring
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
Error:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
Solution 1:
in main program (.cs)
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
Solution 2:
in web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
in main program (.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
reference: https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx

C# - "Login failed for user 'Username'(SQL Server 2014)

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))
{
}
}

C# WinForms not accepting connection string user details

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.

An OLE DB Provider was not specified in the ConnectionString. 'Provider=SQLOLEDB;

i trying to run query using C#, i am getting the following problem
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;
my code
string strConString = System.Configuration.ConfigurationManager.ConnectionStrings["WorkflowConnStr"].ConnectionString.ToString();
string sqlstr = "select * from table"
OleDbConnection myConnection = new OleDbConnection(strConString);
try
{myConnection.Open();}
catch (Exception err)
{ System.Diagnostics.Debug.WriteLine(err.Message); }
OleDbCommand myCommand = new OleDbCommand(sqlstr, myConnection);
OleDbDataReader reader = myCommand.ExecuteReader();
web.config
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password" providerName="System.Data.OleDb.OleDbConnection"/>
any suggestion ?
Try adding this to your connection string,
Provider=SQLNCLI10.1
So it would be;
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password;Provider=SQLNCLI10.1" providerName="System.Data.OleDb.OleDbConnection"/>
Use SqlConnection instead of OleDbConnection.

Login failed for user 'sa'. in connection string

I'm getting the following error:
Login failed for user 'sa'
When I try to connect server by setting value through a string variable:
private SqlConnection getDbConnection = new SqlConnection("Data Source="+dbname+";Initial Catalog="+catname+";User Id=sa;Password=sa;Integrated Security=false");
But when I use the normal connection string with no string variable it works well:
private SqlConnection getDbConnection = new SqlConnection("Data Source=Ali-pc\\;Initial Catalog=master;User Id=sa;Password=sa;Integrated Security=false");
put your connectionstring in web.config file as I show below
<connectionStrings>
<add name="Test" connectionString="data source=Harsh; Initial Catalog=Test ; user Id=sa; password=sa123;"/>
</connectionStrings>
Above "Test" is connectionstringname,you can write your datasource name.Mine is Harsh,so changed it according to yours.Give your database name in inital catalog.
And then put this code in your code behind page load event
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ToString());
It will work.
Maybe the server name and the database name (in the dbname and catname variables) are just wrong?
BTW, i would recommend using the SqlConnectionStringBuilder class.
var sb = new SqlConnectionStringBuilder() { InitialCatalog = catname,
DataSource = dbname,
UserID = "sa",
Password = "sa" };
var dbConnection = new SqlConnection(sb.ConnectionString);

Categories

Resources