I have a code written in JAVA:
String host = "jdbc:mysql://online/find";
String username = "test";
String password = "test";
And its working fine. But I want to use the same database MySQL with C#. And I am doing this:
try
{
string myConnStr = "Server=//online/find; " +
" Port = 3306; "+
" DATABASE=finder; " +
" UID=test;Password=test;";
MySqlConnection MySqlConn = new MySqlConnection(myConnStr);
MySqlDataAdapter MySqlAdapter = new MySqlDataAdapter();
MySqlAdapter.SelectCommand = new MySqlCommand("Select * from finder.Customer", MySqlConn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(MySqlAdapter);
MySqlConn.Open();
DataSet ds = new DataSet();
MessageBox.Show("Connected");
MySqlConn.Close();
}
But I am getting Error: "Unable to connect to any of the specified mysql hosts"
I even tried with
IP address in connection string but still its not working.
I have checked these posts already:
Unable to connect to any of the specified mysql hosts. C# MySQL
unable to connect to any of the specified mysql hosts. c#
According to the documentation should be:
string myConnStr =
"Database=finder;Data Source=//online/find;Port=3306;User Id=test;Password=test";
However for me Connection strings could be hard to remember.
Its very easy to make a mistake when you write it manually.
One advice is to use the server explorer to connect to your database. Then right click on your database icon > select properties ... you will see the connection string copy and paste .
VoilĂ !
Server Explorer:
Properties:
Did you install the MySQl Connector for Microsoft Application. If yes then add a reference to MySql.dll from your C# application, then use the below connection string
string myConnStr = "server=yourMySqlServerHostorIP; port=MySqlPort;uid=username;pwd=password;initial catalog=dbname";
To download mysql connector go to http://dev.mysql.com/downloads/connector/net/.
Let me know if it works.
My first idea about the issue is "this has nothing to do with param names for username and password". You are not getting an error like:
user "null" cant login
Java and C# work on totally different foundation (Oracle vs. Microsoft) I don't know Java but I think the libraries for connecting to a remote location must be different.
I think the host URL you used is the problem:
Server=//online/find;
I use MySQL with my C# projects and I define the host value as:
localhost or 127.0.0.1
an IP address (xxx.xxx.xxx.xxx)
a host url (my.dbserver.com)
here is a working MySQL connection string:
<add name="dbConnNews"
connectionString="server=xx.xx.xx.xx;database=yyyyy;User
Id=zzzzzz;Password=**********;"
providerName="MySql.Data.MySqlClient" />
Try to connect to the server via IDE Server Explorer --> Data Connections and observe the connection string generated.
Related
I have created a server with Unity 2019, collecting some data and I struggle to connect to my MySQL database. The database is stored locally.
I can access my DB in a simple C# project (not Unity) but have no luck with Unity.
Do you have any idea on how to solve this issue ?
So far I found some post about importing dll from the MySQL connector.net :
https://sigitov.de/how-to-add-mysql-capabilities-to-a-unity-application/
https://www.codedojo.com/?p=2132
How do I import MySql Connector into Unity Project?
I added the following dll :
From MySQL Connector.Net 8.0 (in MySQL\ConnectorNET8.0\Assemblies\v4.5.2 folder)
MySQL.Data.dll
BouncyCastle.Crypto.dll
Renci.SshNet.dll
SshNet.Security.Cryptography.dll
Google.Protobuf.dll
From Unity Mono2.0 :
I18N.CJK.dll
I18N.dll
I18N.MidEast.dll
I18N.Other.dll
I18N.Rare.dll
I18N.West.dll
Using this I was able to use MySql.Data.MySqlClient and create a MySqlConnection.
However when I try to open the connection I get :
Error: 0 : Unable to connect to any of the specified MySQL hosts.
I verified the string used to create the MySqlConnection by using the same string in another C# project and it works fine there.
I tried adding charset (Unity3D connection to MySQL error), putting capital letters ... but no improvement.
At this point I don't know if Unity is blocking in some way the connection or if I'm missing something.
It seems that I am not the only one struggling with this (Accessing MySQL database using c# on unity?, https://www.reddit.com/r/Unity3D/comments/902wy3/best_way_to_retrieve_game_data_item_list_stats/, https://www.reddit.com/r/Unity3D/comments/c7b101/is_it_possible_to_use_systemdatasqlclient_in/, https://www.reddit.com/r/Unity3D/comments/8c25mu/unity_server_how_to_connect_to_mysql/).
I am aware that some people use PHP (or some other webserver) as a "middleman" between Unity and MySQL but it sounds a bit overkill for something working just fine in C# outside Unity...
Here is the code I use for the connection to MySQL, connection is a MySqlConnection, private member of my class, I tried those lines in the classic Unity Start function of my class
string dataSource = "localhost";
string port = "3306";
if (connection != null)
{
connection.Close();
}
string connStr = "Datasource=" + dataSource +
";port=" + port +
";username=" + Global.Username +
";password=" + Global.Password +
";database=" + dbName;
connection = new MySqlConnection(connStr);
try
{
Debug.Log("Connecting to MySQL...");
connection.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Just to let you know : I also posted the question on reddit (r/Unity3D)
I'm trying to connect a winforms .net application with an AWS RDS MySQL database but I am having difficulty making the connection. I have read a lot of material about connecting through Microsoft SQL database and through Elastic Beanstalk but I haven't come across the answer I'm looking for... possibly because I'm a noob.
I've looked through a few of these questions:
How to connect to MySQL Database?
https://dev.mysql.com/doc/dev/connector-net/8.0/html/T_MySql_Data_MySqlClient_MySqlConnection.htm
using MySql.Data.MySqlClient;
string connection = "server=localhost; Database=database_URL; User Id=admin;
Password=myPassword";
myConn.Open();
MessageBox.Show("Success");
I'm getting the following error message:
MySql.Data.MySqlClient.MySqlException: 'Unable to connect to any of the specified MySQL hosts.'
Is there something simple that I'm missing? I have copied the database endpoint into the database_URL location. My user id and password are correct. My database is setup on AWS as a MySQL database.
Checking back with ConnectionStrings makes it appear as if your parameter-names are wrong. 'username' should be 'uid' and 'password' should be 'pw'.
In any case I'd suggest using the MySqlConnectionStringBuilder-class to construct your connection string.
var connectionStringBuilder = new MySqlConnectionStringBuilder
{
Server = "<Instance_Ip>",
UserID = "root",
Password = "<Password>",
Database = "<Database_Name>"
};
using (var conn = new MySqlConnection(connectionStringBuilder.ToString()))
The error message is given because can't connect to the host.
In your connection string is given the localhost as the server but your database is on cloud (AWS), so it means that you must specify the database's IP or the domain name pointing to that database, not the local (local means that is in your computer). e.g.
string conn = "server=192.168.0.7; Database=database_name; User Id=admin;
Password=myPassword";
Note that the server IP is provided by AWS, and you'd make sure that ports are enable. The most common port for MySQL is 3306.
Best regards.
Try this,
//This is my connection string i have assigned the database file address path
string MyConnection2 =
"host='localhost';database='databasename';username='myusername';password='mypassword'";
//This is my insert query in which i am taking input from the user through windows forms
string Query = "Your query";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
// Here our query will be executed and data saved into the database.
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
I'm trying to do application to access the database from local file server, but the connection string does not recognize the server location. This is a windows form application, using sqlite. Kindly help me on this one.
File server location will be like this:
\\fileserver\Testdb\maindb.db
Code used:
string server_database_path = #"\\fileserver\Testdb\maindb.db";
string connection_data = "Data Source=" + server_database_path ;
using (var conn = new SQLiteConnection(connection_data))
{
conn.Open();
SQLiteCommand insert_Rec = new SQLiteCommand(query_text, conn);
insert_Rec.ExecuteNonQuery();
conn.Close();
}
Error:
Unable to open database file
I may be wrong but I dont think that directly specifying the .db is correct. When using a normal SQL Server I would specify the instance (or just the server hosting it if it was the default instance).
So, your connection string should look something like
string connectionString = "Data Source=192.168.0.1; User ID=administrator; Password=YOURPASSWORD"
or if you are connecting the machine you are on it should be
string connectionString = "Data Source=127.0.0.1; User ID=administrator; Password=YOURPASSWORD"
You could substitute the 127.0.0.1 for \\localhost
I was confused in doing this, but by changing the slash "\" to "/" it really worked.
When i changed the slash in the path string it started to work fine and everything goes well.
Example: #"//fileserver/Testdb/maindb.db"
In my application, i make a dynamic connection string:
server = "Server = .\\" + this.comboBoxListInstances.SelectedItem.ToString() + ";";
connectionString = server + attachDatabase + databaseName + "Integrated Security = true";
On my laptop (using SQL server 2008 express), the result is:
// server = "Server = .\\SQLEXPRESS;" (I select SQLEXRESS in comboBox)
// attachDatabase = "AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;"
// databaseName = "Database = DATA;";
// so the conectionString is : "Server = .\\SQLEXPRESS;AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
I read registry to find all SQL server Instances and let the user choose which they want.
This conectionString work fine on my laptop and my friend who use SQL server express too. However, when i run my app on another friend's laptop with SQL server 2008 R2 installed, it throws an exception:
It say the connection string is invalid, It is :
"Server = .\\MSSQLSERVER;AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
when I try to temporarily disable comboBoxListInstance and use this conectionString
"Server = (local);AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
The app works! So, I think there is a difference between the conection string for SQL server express and SQL server. Is it right? There is a question similar to mine here, and they say that there is no difference. If they are right, what is the problem of my connectionString?
P/S: sorry for my bad grammar
It looks like you just proved that SqlExpress installs its default named instance as "MSSQLSERVER" where as full sql installs an unnamed default instance of blank.
(local) means " .\ " " 127.0.0.1" WHATEVER instance is at 1433.
.MSSQLEXPRESS means explicitly .\MSSQLEXPRESS which may or may not be the (local) default instance.
As An Aside usually the most relevant difference at this point is that regular SQL will install with the ports open and TCP clients ready to go.
SQL Express will only allow local "dev" type of connections until you activate the external ports and client protocols.
How to get server name through code if SQL Server (Standard Edition) is installed.
We pass the server name while creating a connection string to connect SQL Server. Can we retrieve this value through code?
string sqlConnectionString = string.Format(
"user id={0};password={1};server={2};Trusted_Connection=no;database=TestDB;
connection timeout={3}",
dirDBinfo.UserName, dirDBinfo.Password, "ServerName", dirDBinfo.TimeOut);
I'm not sure I understand what you want.
If you already have a connection string, and you are trying to extract the server name from it for use elsewhere, you can reverse-engineer it like so:
var parser = new SqlConnectionStringBuilder(connectionString);
var serverName = parser.DataSource;
If you are constructing your connection string for the first time, then:
If you know that you want to connect to the SQL Server on the machine that your client code is executing on, then just use (local) for the server name. If the SQL Server has an instance name, then specify it like this: (local)\myinstancename.
If you don't know in advance what server to connect to, then it's up to you to obtain that information from somewhere else.
Can't you just execute SELECT ##SERVERNAME against this connection?
Is the server on the local computer?
If so, set the server name to localhost.
If not, use SqlDataSourceEnumerator.
Also, instead of building a connection string using String.Format, you should use a SqlConnectionStringBuilder. This will handle values with semicolons.
For example:
var builder = new SqlConnectionStringBuilder();
builder.UserID = dirDBinfo.UserName;
builder.Password = dirDBinfo.Password;
builder.Server= "localhost";
builder.UserID = dirDBinfo.UserName;
builder["Trusted_Connection"] = "no";
builder.Database = "TestDB"
builder.ConnectTimeout = dirDBinfo.TimeOut;