I have a java program that connects to a MySql database and it's working fine.
Now I want to convert it to a C# program, but I keep getting the error "Unable to connect to any of the specified hosts".
I've already followed the following solutions:
Connect to MySql with C#
C# MySqlConnector
Configure the ODBC DNS
And the reference to MySql.Data has been added to the project.
Here is the code to connect to the database:
string connectionString = string.Format(
"SERVER={0}; DATABASE={1}; UID={2}; PASSWORD={3};",
"jdbc:mysql://" + host + ":" + port, dbName, userName, password);
// Prepare connecting to the database.
myConn = new MySqlConnection(connectionString);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = #"SELECT * FROM table_name";
myConn.Open(); // <- MySqlException: Unable to connect to any of the specified MySQL hosts.
MySqlDataReader reader = command.ExecuteReader();
List<string> exampleStore = new List<string>();
while (reader.Read())
{
// Just an example for storing data.
exampleStore.Add(reader.GetString(0));
}
The java version connects to the same server with the same values as I used here, so please don't suggest checking if the server is online.
So the problem must be in my C# code, I noticed Class.forName("com.mysql.jdbc.Driver").newInstance ();
In the java code. Seems like the driver is made active here, maybe C# needs to do something similar that I'm missing?
Edit: So the connection string should be: string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));
Was using some extra elements from the java version, din't think they would cause these problems. Thanks for the help guys.
The standard connection string is:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;.
Please note that the port is specified separately, with Port=1234, not in the Server field. Also, eliminate jdbc:mysql: from the start of the server field, as it's specific to the JDBC driver; use a normal URI string. Nothing else should be needed.
Your connection string is wrong.
Try:
string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));
Related
I am trying to connect to the MySQL database using this code client_v is the name of the table I want to get data from.
I went through a lot of similar questions here but I really haven't found an answer to this question.
using MySql.Data.MySqlClient;
private void Form1_Load(object sender, EventArgs e) {
try {
string connetionstring = "Server=a029um.forpsi.com;Uid=userlogin;Pwd=userpassword";
string mysql = "SELECT * FROM dbname.cilent_v";
MySqlConnection conn = new MySqlConnection(connetionstring);
MySqlCommand command = new MySqlCommand(mysql, conn);
conn.Open();
MySqlDataAdapter dtb = new MySqlDataAdapter();
dtb.SelectCommand = command;
DataTable dtable = new DataTable();
dtb.Fill(dtable);
dataGridView1.DataSource = dtb;
} catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
The error it is returning:
Unable to connect to any of the specified MySQL hosts.
Initially, I can see that you miss the Database part in your connection string.
Be sure that your connection string is valid (including valid user name and password)
For MySql, you can find here all example list
https://www.connectionstrings.com/mysql/
I also noticed that your server is hosted on the cloud (most likely shared hosting) so you need to contact the service provider and ask them to add your computer's public IP to their firewall to accept your connection.
The better practice, for the development environment, install the MySql engine and WorkBench on your local PC, and finally when you reach the point to deploy, that time change the connection string to connect to the cloud-hosted Database.
To install MySql Engine see
https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en
To install WorkBench (The database management studio) see https://dev.mysql.com/doc/workbench/en/wb-installing-windows.html
How to use WorkBench, just google some training videos on the internet.
I have two SQL Server databases, server name are sql1 and sql2.
When I switch database from sql1 to sql2 (using HaProxy), my application still keeps the old SQL connection to server sql1.
However, other applications (using Linq-to-SQL) can get the new SQL connection to sql2.
Please see my code below that's I using to get connection to SQL Server:
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
conn.Open();
//do something...
conn.Close();
return data;
}
}
What's my problem? How can I resolve this? Thanks!
You need to know the HAProxy listen configuration, maybe your HAProxy has exceptions programmed, or the redirection only works if you use an specific IP address destination or come from an specific IP range. Please compare the connections string used in each case.
https://www.stevefenton.co.uk/2016/11/load-balancing-microsoft-sql-server-with-haproxy/
I'm kinda new to C# and i'm currently just trying to connect to a remote SQL server which will then simply show the license key from the licensekeys table and show it in a MessageBox if it matches the license key in textBox1 all from the click of a button. (So basically like a login with a username and password except I just want a login with a license key)
What I have at the moment:
SqlConnection connect = new SqlConnection("Data Source= MYSERVERIPHERE\\MSSQLSERVER2008;Initial Catalog=MYDB;User ID=MYUSERID;Password=MYPASSWORD");
SqlCommand = "SELECT licensekey FROM licensekeys WHERE licensekey = textBox1.Text";
Not sure what to do from here and would appreciate it if someone could guide me, cheers.
If the connection works otherwise, the issue can be that the lisence key is TEXT field and the string needs to be inside apostrophes (c++ string as an example):
SqlCommand = "SELECT licensekey FROM licensekeys WHERE licensekey = '" +
textBox1.Text + "'";
try this:
SqlConnection connect = new SqlConnection("Data Source= MYSERVERIPHERE\\MSSQLSERVER2008;Initial Catalog=MYDB;User ID=MYUSERID;Password=MYPASSWORD");
SqlCommand = string.Format("SELECT licensekey FROM licensekeys WHERE licensekey = {0}" , textBox1.Text);
I am assuming that the connection string is correct and can really connect to the remote server
Wait... before you copy and paste the answer to you code file, please note there is a vulnerability called SQL injection!!
For the MySQL connection string in C# you can search for it, or use a SQL connector developed by MySQL team or community out there
https://www.connectionstrings.com/mysql/ , here is a example extracted from it:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
And for the real code, I am sure that there is a SQLCommand, which you are using it already, and SQLParameter
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v=vs.110).aspx to use, and it help you prevent SQL injection
Example: (assuming using SqlConnection works for MySQL, not sure; if it does not work, please use MySQL connector, and read corresponding docs)
var command = connect.CreateCommand();
command.CommandText = "SELECT licensekey FROM licensekeys WHERE licensekey = #license";
var license = new SQLParameter("#license", SqlDbType.Char) // let's assume the license only contains ASCII.
{
Value = textBox1.Text
};
command.Parameters.Add(license);
command.ExecuteScalar(); // or command.ExecuteScalarAsync();, assuming you only want 1 row of record.
You will never want someone with license key abc OR 1=1 and allow them to login to your system :(
I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.
My code is as follows:
string constring = "Data Source=132.186.127.169"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
SqlConnection con;
con = new SqlConnection(constring);
con.Open();
string query="SELECT * from CadPoolProjectTable1";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("selected");
con.Close();
I am getting error at the line con.Open();. The error is:
A network-related or instance-specific
error occurred while establishing a
connection to SQL Server. The server
was not found or was not accessible.
Verify that the instance name is
correct and that SQL Server is
configured to allow remote
connections. (provider: Named Pipes
Provider, error: 40 - Could not open a
connection to SQL Server)
You are missing a ';' after the server name in the connection string.
string constring = "Data Source=132.186.127.169"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
It should be
string constring = "Data Source=132.186.127.169;"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
The error says that your app was not able to connect to the server. I would do the following.
Check for the server address (on a quick look it looks good)
Connect using management studio and in your case it should have worked.
It means the issue is with the code. Since you are concatenating the string I would debug the code and see what the end result for the connection string is.
Tip:If it is a web application add the connection string to web.config file. More info here How to: Read Connection Strings from the Web.config File
You're missing a semicolon in your connection string
Data Source=132.186.127.169;"+ "Initial...
^
If you need to build the connection string yourself you can use the SqlConnectionStringBuilder class. That way you won't to be as troubled by these subtle mistakes.
Your connection string is wrong:
string constring =
"Data Source=132.186.127.169;Initial Catalog=CadPool1;Integrated Security=True";
You don't need to concatenate the strings together, but more importantly, you were missing the semi-colon ";" between the data source and the initial catalog settings.
First, you are missing a ; (semicolon) between Data Source and Initial Catalog.
Second, if this is a newly installed SQL Server instance, you may need to go into SQL Server Configuration Manager, and enable the protocol(s) you'll need.
Please check if you can ping the server mentioned via cmd
Also try telnet to the server from your machine.
One more thing to check would be port the server is configured for if its not the default one you will have to add the port as 132.186.127.169,XXX
Servername in the connection string is wrong. and also since there are no dynamic values you don't need string concatenation. Change it to:
string constring = "Data Source=132.186.127.169;
Initial Catalog=CadPool1;
Integrated Security=True";