Unable to connect to any specified mysql C# - c#

I can't connect to my sql server, i tried some fixes from stackoverflow and google and it didn't help me. Thanks.
connString = "SERVER ='''myserverip''';PORT=3306;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Connection success");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
To configure myuser I used this on my linux vps.
CREATE USER 'myuser'#'localhost' IDENTIFIED BY 'mypassword'; CREATE USER 'myuser'#'%' IDENTIFIED BY 'mypassword'; GRANT ALL ON *.* TO 'myuser'#'localhost'; GRANT ALL ON *.* TO 'myuser'#'%';
i tried : Unable to connect to any of the specified mysql hosts. C# MySQL ( i tried to use MySqlConnectionStringBuilder, don't specify the port, instead of password in connection string i typed psw);
Disable my pc firewall, disable linux server firewall

MySqlConnectionStringBuilder does enable you to specify port. Just tested, this works just fine:
MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder();
csb.Server = "192.168.1.105";
csb.Port = 3307;
csb.Database = "test";
csb.UserID = "me";
csb.Password = "mypassword";
cn = new MySqlConnection(csb.ToString());
cn.Open();
Are you quite sure your MySql server actually accepts incoming connections over TCP? By default that is disabled.

So, after searching on google how to setup sql connection in linux, and trying different setups hardly I fixed it so I want to share with stackoverflow how I fixed it. Thanks for help #Avo Nappo.
First you need to comment out the line #bind-address from your sql config.
The accepted answer here :MySQL root access from all hosts .
Then I create a user using this command CREATE USER 'golden'#'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'#'%';
And in c# I used my default connection string that is in the question. I don't know why but MySqlConnectionStringBuilder dose not work on my pc. I hope this will help someone. Have a nice day and keep coding.

You must go in your Remote MySQL in your C-Pannel and Add Access Host first and change this code
connString = "SERVER ='''myserverip''';PORT=3306;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword";
to
connString = "SERVER =*Put here your Hostname with Port*;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword;";
Or use this Method
MySqlConnectionStringBuilder ConStD = new MySqlConnectionStringBuilder();
ConStD.Server = "Hostname that get from Manage Access Hosts";
ConStD.Port = Port that get from Manage Access Hosts;
ConStD.Database = "YourDatabaseName";
ConStD.UserID = "yourUsername";
ConStD.Password = "yourpassword";
try
{
MySqlConnection conn = new MySqlConnection(ConStD.ToString());
conn.Open();
MessageBox.Show("connection Success");
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
It's Must working For You

1-Un check all Firewall and Network protection settings
2-Go in database management system running icon like wamp green icon
3-Go to Mysql CMD
3a-
CREATE USER 'muzamil'#'%' identified by 'muzamil';
grant all privileges on *.* to 'muzamil'#'%';
flush privileges;
These three commands run one by one
4-Windows Defender Firewall
then Click on Advance settings
==> Inbound Rules
->Enable riles Remote Desktop TCP All Rules
5:
C:\wamp64\alias
open this File then
change local to
==> Require all granted
==> Allow from all
Your remote server
will work with c# application

Related

SQL Server Connection String in Trusted Connection format doesn't work

first time using sql with C# and I seem to be running into an unbreakable wall. I'm trying to connect to my database which is on a different server on the same domain. This is all within a winform app. Also the windows account I am using for running this winform application has read and write permissions to the sql database already (Same domain account). I've set my connection string in my app.config as follows following the advice from connectionstrings.com
<connectionStrings>
<add name="my_db" connectionString="Server=10.xx.xx.xx;Database=my_db;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have the following method in Helper.cs where I am setting the Connection string from the config file.
public static string CnnVal(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
Lastly, I have the following method in its own class, DbConnect.cs, and this method is called when I click a button on a form.
public void TestConnection()
{
try
{
using (var connection = new SqlConnection(Helper.CnnVal("my_db")))
{
var query = "Select 1";
System.Diagnostics.Debug.WriteLine($"Executing {query}");
var command = new SqlCommand(query, connection);
System.Diagnostics.Debug.WriteLine($"successful connection");
command.ExecuteScalar();
System.Diagnostics.Debug.WriteLine($"Successful query");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"failure {ex.Message}");
}
}
I set breakpoints on "var command" and "command.ExecuteScalar();" lines and when looking at my Watch tab in visual studio, I can see that my connection is not opened and this leads to an InvalidOperationException from SqlCommand. I'm not sure why this is happening. I used sql server migration assistant this morning to migrate the server from mysql over to sql and my info all worked then (windows auth, ip, database name). What could the outlier be here? Do I have to put the port number in my connection string somewhere? I'm using the default 1433 port. Any help would be appreciated. Thanks

C# Winforms connection to MySQL AWS Database

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();

SQL Server : CREATE DATABASE permission denied in database 'master'

I am getting this error:
CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file C:\APP_DATA\WRESTLING.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
but I give my service the administrator account:
So, why is it being denied?
Here is my code:
void ConnectToDb()
{
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = #"(localdb)\MSSQLLocalDB";
connStringBuilder.InitialCatalog = "WRESTLING.MDF";
connStringBuilder.Encrypt = true;
connStringBuilder.ConnectTimeout = 30;
connStringBuilder.AsynchronousProcessing = true;
connStringBuilder.MultipleActiveResultSets = true;
connStringBuilder.IntegratedSecurity = true;
string temp = #"Server=EC2AMAZ-FN5N011\MSSQLSERVER;Database=C:\APP_DATA\WRESTLING.MDF;Trusted_Connection=True;";
string temp1 = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
string temp2 = #"Data Source = (local); AttachDbFilename = C:\APP_DATA\WRESTLING.MDF; Integrated Security = True; Connect Timeout = 30;";
conn = new SqlConnection(temp2);
comm = conn.CreateCommand();
}
Also, I am using an IIS Service to connect to the SQL database and that IIS is an Administrator too .
Update:
[2
[3
Your code is the mix of connection strings to different servers. So it's not clear to which one you want to connect.
string temp and string temp2 attempt to connect to the default local instance of SQL Server. You should not attach nothing to it as there is already the database in question attached to this instance.
Your string temp1 attempts to connect to localdb, it's another server, not that one that we see on your screenshot, and here yes you can specify the file to attach.
Now it seems that you are trying to connect to the default instance under IIS APPPOOL\.NET v4.5 (your IIS is running under this account), this account is not the same with that you used to connect at the screenshot.
You should map this login to server (for now it's not mapped or at least not explicitely) and then map it to your database and make it db_owner:
create login [IIS APPPOOL\.NET v4.5] from windows;
use WRESTLING;
go
create user [IIS APPPOOL\.NET v4.5] from login [IIS APPPOOL\.NET v4.5];
exec sp_addrolemember 'db_owner', [IIS APPPOOL\.NET v4.5];

MySQL Connection with C#

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.

System.InvalidOperationException: Internal Connection Fatal Error. when opening sql connection

I've just started playing around with SQL on C#, and I'm trying to connect to a remote SQL server. I've added my IP to the list of hosts that have remote access permission.
My code keeps producing this error:
System.InvalidOperationException: Internal Connection Fatal Error.
at System.Data.SqlClient.TdsParserStateObject.TryPocessHeader<>
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer<>
at System.Data.SqlClient.TdsParserStateObject.TryReadByteArray<.Byte[] buff, Int32 offset, Int32 len, Int32& totalRead>
The trace is actually longer than that, but those are the first few lines.
This is the code that's causing the error (My actual connection string has the correct username, password, and database name):
connectionString = "Data Source=173.254.28.27,3306;Network Library=DBMSSOCN;Initial Catalog=myDatabase;User Id=myUserName;Password=myPassword;";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
try { myConnection.Open(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
Any help would be greatly appreciated.
Thanks!
EDITED
If you are using MySQL Server then your connection string is wrong!
try this connectionString :
_connectionStr = new MySqlConnectionStringBuilder
{
Server = "173.254.28.27",
Database = myDatabase,
UserID = myUserName,
Password = myPassword,
ConnectionTimeout=60,
Port = 3306,
AllowZeroDateTime = true
};
_con = new MySqlConnection(_connectionStr.ConnectionString);
try
{
_con.Open();
}
catch
{
Console.WriteLine("Error, help i can't get connected!");
}
If you are using SQLServer try disabling Connection Pool through connection string!
by adding :
Pooling=false
Good luck!
Create a udl file, if it connects then the problem is the code / application, if it does not connect, then it's your firewall, connections string, dll library etc. Well the important thing here is probably the connection string. Do the following: create an empty text file and rename it "myconnection.udl". Now double click on the file and it will launch an applet. You can configuer the connection to your database and test it. (it will pick up registered connection libraries etc). If it give OK, then open the udl file in notepad, you will see the correct connection string. Paste to your app connection settings. UDL files are generally misunderstood. They are simply a text file that holds the connection settings. They then call the connection dll. If the udl file works then you have a correct connection string 100%

Categories

Resources