cannot open database - c#

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

Related

Connect and insert data from my computer to server's MySQL DB table with the help of C#.NET

I want to connect with a server's MySql DB(cpanel) . Though there are no errors every time I'm getting a message for Messegebox : unable to connect to any of the specified any of the MySql hosts.
using MySql.Data.MySqlClient;
connString = "SERVER = ********;PORT=3306;DATABASE=********;UID=**********;PASSWORD=*********";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Server is online");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{ MessageBox.Show(ex.Message);}
If you try to connect to your MySQL server externally, external connections need to be enabled.
Be aware that it is a security hole if you provide your app to others which contain the DB information. To go around that, you need to create a Web-API.
The first step to connect to your app to a remote server MySql Server is verify if it allows external connections, for default the root user is locked, to allow local you can try to connect with the root user typing the following command in MySql:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
'root': You can change it with your user.
'%': allows all connections, you can limit it typing an IP.
Second step is verify your MySql .net connector
Cheers!
I would look into using ConnectionStringBuilder. Also note the use of 'using'. This will ensure resources are disposed once finished with.
private MySqlConnectionStringBuilder sConnString = new MySqlConnectionStringBuilder
{
Server = "",
UserID = "",
Password = "",
Database = ""
};
private void Test(){
// open connection to db
using (MySqlConnection conn = new MySqlConnection(sConnString.ToString()))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
try
{
conn.Open();
cmd.CommandText = "SELECT * FROM foo WHERE OrderID = #OrderID";
// Add any params
cmd.Parameters.AddWithValue("#OrderID", "1111");
cmd.Prepare();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
}

Error while connecting to sql through windows authentication

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();
//...
}

Connecting C# Windows Form Application to Sql Server

I'm connecting my windows form application to SQL server but I get this error "SqlException was unhandled" when I start the program.
Here is my code:
void ShowEmployees()
{
using (SqlConnection Connect = new SqlConnection("Data Source=(local);" + "Database='SanMarDryCleaners';" + "Integrated Security=SSPI;"))
{
string strEmployees = "SELECT * FROM employees;";
SqlCommand cmdEmployees = new SqlCommand(strEmployees, Connect);
SqlDataAdapter daEmployees = new SqlDataAdapter();
daEmployees.SelectCommand = cmdEmployees;
DataSet dsEmployees = new DataSet("EmployeesSet");
daEmployees.Fill(dsEmployees);
Connect.Open();
dgvEmployees.DataSource = dsEmployees;
dgvEmployees.DataMember = dsEmployees.Tables[0].TableName;
}
}
Here is the screenshot:
The error suggest that it can't find the SQL Server. And that makes sense because you are using a SqlConnection class which is for Microsoft SQL Server only. You have to use MySQL libary.
Download it from this site:
http://dev.mysql.com/downloads/connector/net/
The error points to a problem while connecting to the server.
A SqlConnection is for SQL-Servers. Use a library specific to MySQL and a MySqlConnection.
See:
Connector/Net Installation
MySQL Connector/Net connection strings

Error: Invalid object "tbl_name"

I am creating a small project by using winforms in C# using Visual Studio 2010 and SQL Server 2008 - When I am creating setup and running it on the same computer it is working very well - but when I am running it on a different computer I got an error (Invalid object "tbl_name")! I'm using (SQL Server authentication) and my connection code is:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = ".";
builder.InitialCatalog = "Sectors";
builder.IntegratedSecurity = false;
builder.Password = "123";
builder.UserID = "MAK";
builder.AsynchronousProcessing = true;
builder["Trusted_Connection"] = true;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = builder.ConnectionString;
conn.Open();
Please help me find the cause of the error and resolve it.
You could remove the statement "builder["Trusted_Connection"] = true;" and also try to change the connection settings (like DataSource to localhost).

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

Categories

Resources