I'm getting error:
Could not establish a connection to database
when I connect with MySQL .NET connector. I'm fully sure of that the username is right, the password is right, the database is right, and the server is right. Here's the code:
mysqlCon.ConnectionString = "Server=(servername);Username=(username);Pwd=(rightpassword);
Database=(rightdatabase)";
try
{
mysqlCon.Open();
}
catch (Exception ex)
{
MessageBox.Show("Could not establish a connection to database!");
}
Shouldn't you use Uid instead of Username? At least connectionstrings.com says so :)
And also check what port is your MySQL running at. You might need to add port number to your connection string if you aren't using the default one - 3306.
I use:
public MySqlConnection NewConnection(string host, int port, string db, string user, string pwd)
{
string cstr = String.Format(
"SERVER={0};PORT={1};DATABASE={2};UID={3};PWD={4}",
host, port, db, user, pwdd);
MySqlConnection conn = new MySqlConnection(cstr);
try { conn.Open(); }
catch (Exception ex)
{
conn = null;
}
return conn;
}
Make sure that the database is reachable from the machine you're running the code.
Use telnet
telnet <server> 3306
or MySQL command line client
mysql -u <user> -h <server> -P <port> -p
Related
I want to connect to mysql with my computer name as host.
I get this error :
unable to connect to any of the specified mysql hosts
When i change the host with localhost or 127.0.0.1. it's work fine.
I test the connection directly in mysql workbench with my computer name : COMP-18TN. MySQL Workbench could connect to that server. But not my c# code.
You find as bellow my code :
string host = "COMP-18TN";
string DatabaseName = "Cars_DB";
string UserName ="root_name";
string Password ="pass";
string connString = string.Format("Server={0}; database={1}; UID={2}; password={3}",
host, DatabaseName, UserName, Password);
MySqlConnection conn = new MySqlConnection(connString);
try
{
conn.Open();
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
You can try adding an entry in your hosts file located in C:\Windows\System32\drivers\etc\hosts:
127.0.0.1 COMP-18TN
This way your computer name will resolve to the local IP which you know works.
I have a database on my local machine on SQL Server Management studio.
The database connection information is as follows.
In my c# application, I have a connection string to connect to this database. I get an error though saying my connection string is incorrect. I have tried a number of different ones.
This is my function to connect to a database.
public virtual void openConnection()
{
con = new SqlConnection();
con.ConnectionString = "Server=DESKTOP-8UDMQUI\\WILLIAMSQL;Initial Catalog=team3db;TrustServerCertificate=true;";
try
{
con.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I have two \ in the server name because when I only have one, it has a red squiggle line under it throwing me an error on visual studio.
What should my connection string be? Note there is no password on this database.
Replace TrustServerCertificate = true; with Integrated Security = true
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;
}
}
}
}
I'm trying to connect with C# code to a SQL Server database hosted on gear host using the System.Data.SqlClient library, but it doesn't work, I get an error "Server does not exist or connection refused."
Maybe I need do install some driver? Or is there anything wrong with my code?
string connetionString = "Data Source=mssql.gear.host:1433;Initial Catalog=databasename;User ID=userid;Password=mypassword";
SqlConnection cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
Console.WriteLine("Connection Open!");
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
when removing the port it works ,obviously the database in gear host doesn't use a port
I have a Windows XP machine used to create .Net applications with VS 2008.
I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.
I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.
I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.
What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.
I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.
Any help or suggestions are greatly appreciated. Thank you in advance.
//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";
public Oracle()
{
InitializeComponent();
}
//Methods
private void TestMyOracleConnection()
{
OracleConnection Conn = new OracleConnection(CONNSTR);
try
{
Conn.Open();
MessageBox.Show("Oracle Connection Established", "Success");
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
finally
{
Conn.Close();
MessageBox.Show("Oracle Connection Closed", "Success");
}
}
private void buttonTestConnection_Click(object sender, EventArgs e)
{
TestMyOracleConnection();
}
You might want to try something like:
connection string:
Data Source=DBNAME;User ID=zahid;Password= abc123;Persist Security Info=True;Unicode=True;
Now look in the tnsname.ora file on your PC. It will be somewhere under your local Oracle Client installation. You're looking for something like:
DBNAME =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1510))
(ADDRESS = (PROTOCOL = TCP)(HOST = OracleServerName)(PORT = 1514))
)
(CONNECT_DATA =
(SERVICE_NAME = DBNAME)
)
)
You're looking to replace DBNAME and OracleServerName with your own. Don't forget, DBNAME is the name of the main database, not one of the schemas (the entity with all the tables and procedures, etc) under it.
Assuming you are using ODP.Net, you can try a connection string such as the following (taken from a web.config):
<add name="OdpConnection" connectionString="Data Source=xe;User Id=some_user;Password=some_password; Promotable Transaction=local"
providerName="Oracle.DataAccess.Client" />
You can read this connection string from the web.config in your code using something like this:
string connectionString = ConfigurationManager.ConnectionStrings["OdpConnection"].ConnectionString;
It's a good practice to avoid putting connection strings directly in code, since to change them requires a re-compile. By putting them in a config file, such as web.config or app.config, you can change them without having to re-compile your library or exe.
try
{
Conn.Open();
MessageBox.Show("Oracle Connection Established", "Success");
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Oracle Connection Failed!");
}
finally
{
Conn.Close();
MessageBox.Show("Oracle Connection Closed", "Success");
}
You have pottential problem here: if conn.Open() fails (so connection is not opened) in finally you call conn.close(), but connection isn't opened - so it also fails, but it is now outside try catch. You need check for
if (Conn!=null && Conn.IsOpen())
Conn.Close();
Connection string for oracle:
Data Source=TORCL;User Id=myUsername;Password=myPassword;
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
More here