Error while connecting to sql through windows authentication - c#

I am using the following code to connect to sql throgh windows authentication.
string connctionstring = "connectionString={0};Database={1};Integrated Security=SSPI;";
string _connctionstring = string.Format(connctionstring, datasource, initialCatalogue);
SqlConnection _connection = new SqlConnection(_connctionstring);
_connection.Open();
But i am getting the following error. Help please.I am able to login through sql server.

The connection string format is not correct
Change to this:
string connctionstring = "Data Source={0};Database={1};Integrated Security=SSPI;";
Or
string connctionstring = "Server={0};Database={1};Integrated Security=SSPI;";

While Peyman's answer does cover the basic issue (connectionString is not a valid key for the string) a better solution is to use a SqlConnectionStringBuilder, this will also help you do proper escaping if you have odd characters in your string (for example if your database name contained a space)
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = datasource;
scsb.InitialCatalog = initialCatalogue;
scsb.IntegratedSecurity = true;
//You also really should wrap your connections in using statements too.
using(SqlConnection connection = new SqlConnection(scsb.ConnectionString))
{
connection.Open();
//...
}

Related

How can I fix "Keyword not suported: metadata" when opening a SQL Connection?

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.

How to open a MySql connection with TextBox inputs in C#

What I want to do is have text boxes for the user to input the required fields for the connection to the MySQL table, Here is the code I currently have.
public partial class Form1 : Form
{
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = serverTextBox.Text;
conn_string.UserID = userTextBox.Text;
conn_string.Password = passwordtextBox.Text;
conn_string.Database = dataBaseTextBox.Text;
using (MySqlConnection mcon = new MySqlConnection(conn_String.ToString()));
MySqlCommand mcd;
MySqlDataAdapter mda;
//-----open connection-----//
public void openCon()
{
if (mcon.State == ConnectionState.Closed)
{
mcon.Open();
}
}
//-----close connection-----//
public void closeCon()
{
if (mcon.State == ConnectionState.Open)
{
mcon.Close();
}
}
}
I really have no idea how to setup a MySQL connection properly and this was my (failed) best guess.
here is a new picture that might help http://prntscr.com/bgubj5
There should be a lot of reasons of Your problem. You posted only small piece of code, which is not enaught. If You want to connect do database consider following steps:
-make proper connection string (it depends on the database)
-connection string can be make from user inputs, but must be known before calling MySqlConnection
so, firstly save the user inputs to variable, make connectionstring of them, and finally pass it to MySqlConnection constructor
PS. this would help with making connectionstring: https://www.connectionstrings.com/
What exceptions does it throw?
Build the connection string first. Set a breakpoint and check if it looks good.
Or an even better approach will be to use the MySqlConnectionStringBuilder object
your code will look like this:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = serverTextBox.Text;
conn_string.UserID = userTextBox.Text;
conn_string.Password = passwordtextBox.Text;
conn_string.Database = dataBaseTextBox.Text;
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{
//query whatever you want, be aware of SQL injection
}

ConnectionString for SQL Server

I have xampp installed in my computer. I am trying to access data with ADO.Net. The connection string I am using is given below:
string connectionString = "Server = localhost; Database = magento; User Id = magento; Password = abcd;";
SqlConnection con = new SqlConnection(connectionString);
string cmdString = "SELECT date_added,title,description,url FROM adminnotification_inbox";
SqlDataAdapter da = new SqlDataAdapter(cmdString, con);
ds = new DataSet();
da.Fill(ds,"prog");
dt = ds.Tables["prog"];
currRec = -1;
totalRec = dt.Rows.Count;
button3.Enabled = true;
I am able to log in with the above user id and password in phpmyadmin, but cannot access the database with the above connection string. please help. Thanks in advance.
MySQL has its own ADO.NET connector: http://dev.mysql.com/downloads/connector/net/6.6.html#downloads
If you use that, you can create a MySqlConnection: http://dev.mysql.com/doc/refman/5.5/en/connector-net-tutorials-intro.html
The basic SqlConnection is used for Microsoft's own SQL Server products.
9-22-14 - Hope others see this if you don't:
You need a driver in your connect string I believe. "MySQL ODBC 3.51 Driver" is the Window's driver name.
string connectionString ="Driver={MySQL ODBC 3.51 Driver}; SERVER= .... ok put the rest of your connect string here.
Note: this is the string to connect to a MySQL db using MS Access VBA:
Dan

cannot open database

Not sure why this is failing...I'm sure it's my fault. Any help would be greatly appreciated.
I'm getting the classic
Cannot open database "Northwind" requested by the login.
The login failed. Login failed for user 'MyMachine\MyUserName'.
I can login just fine using windows authentication through SQL Server Management Studio.
I checked in SQL Server Management Studio to make sure that my user has permission to use the Northwind database. I also tried most of the other responses to this question posted here on stackoverflow.
This is my code:
SqlConnection dataConnection = new SqlConnection();
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = ".\\SQLExpress";
builder.InitialCatalog = "Northwind";
builder.IntegratedSecurity = true;
dataConnection.ConnectionString = builder.ConnectionString;
dataConnection.Open();
...
.
I'm using SQL Server 2008 Express
In your MS SQL Studio right Click the Server and go to properties Security and select SQL Server and Windows Authencation mode
then restart your server.
in your server. go to Security folder and create a new Login
enter the Username and Password. just uncheck Enforced Security (for testing purpose only)
go to User Mapping and check the database(NorthWind) you want to handle under the new Login account then db_accessadmin
Click OK
and try your code
SqlConnection dataConnection = new SqlConnection();
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "UNKNOWN01-PC\\SQLEXRESS2008R2";
builder.InitialCatalog = "Northwind";
//builder.IntegratedSecurity = true;
builder.UserID = "testlogin";
builder.Password = "1234";
dataConnection.ConnectionString = builder.ConnectionString;
dataConnection.Open();
}
catch (Exception)
{
throw;
}
i suspect that the real issue here is the SqlConnectionStringBuilder but i can't explain. im just a beginner. :)
I m just writing this so that I dont fall into the same trap again and again ... The default name of the database is "NORTHWND" and not "NORTHWIND"
The name is auto created by windows sql server while importing the .bak file from the oficial site.
So this is ok
static string connectionString = "data source=GMDESK028\\SQLSERVER2;initial catalog=NORTHWND;Integrated Security=SSPI;";
Try doing it this way, it's always worked for me, simpler too as you can create a new SQL connection object directly from a connection string by just specifying the string as a parameter, like this:
string connectionString = #"Server=server\instance;Database=Northwind;Integrated Security=True";
SqlConnection dataConnection = new SqlConnection(connectionString);
try
{
dataConnection.Open();
}
catch (sqlexception e)
{
Messagebox.Show("Error");
}

Database Connection String Info

In .Net is there a class in .Net where you can get the DB name, and all the connection string info without acutally doing a substring on the connection string?
EDIT:
I am not creating a connection I am attempting to get info out of the connection string. So I am basicly looking for something that takes a connection string arg and has accessors to dbName, connection type, etc....
You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:
Given
string connectionString = "Data Source = .\\SQLEXPRESS;Database=Northwind;Integrated Security=True;";
You could do...
System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
builder.ConnectionString = connectionString;
string server = builder["Data Source"] as string;
string database = builder["Database"] as string;
Or
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.ConnectionString = connectionString;
string server = builder.DataSource;
string database = builder.InitialCatalog;
After you initialize the connection with the connection string, you can get those information from properties of the initialized connection object.
Check System.Data.Common.DbConnection.
ConnectionInfo connectionInfo = new ConnectionInfo ();
connectionInfo = logOnInfo.ConnectionInfo;
connectionInfo.DatabaseName = database;
connectionInfo.ServerName = server;
connectionInfo.Password = password;
connectionInfo.UserID = user;
EDIT: Looks like Nathan beat me to it, as mine is from the same page.
EDIT AGAIN: I should note that ConnectionInfo is in the CrystalDecisions.Shared namespace. As for how to get it from a generic DB connection, I'm not sure.
Yep ConnectionInfo
http://msdn.microsoft.com/en-us/library/ms226340(VS.80).aspx
EDIT: I, along with Chris, realized that this is only works if you have the Crystal Reports namespaces imported. Otherwise I'm not sure
if you build your connection string using the Connection string builder (e.g. OracleConnectionStringBuilde, and it will be different for different database), in that case easily retrieve the information out of it.
here it explained:
http://msdn.microsoft.com/en-us/library/ms254947.aspx
SqlConnection sq = new SqlConnection(ConnectionString);
Reference
Done with "using" statement (from MSDN)
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}

Categories

Resources