unable to connect to other machine's mysql server using C#? - c#

i need to connect to the other machine's mysql server using C# coding,below is my coding:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace c_mysql
{
class Program
{
static void Main(string[] args)
{
string connection = "SERVER=192.168.1.5; Database=b2b; Uid=root;";
MySqlConnection con = new MySqlConnection(connection);
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from area",con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Console.WriteLine("connection successfull");
}
else
{
Console.WriteLine("not connected...");
}
}
}
}
the ip address 192.168.1.5 is the ip address of other computer which is in LAN,I am able to connect through 192.168.1.5/phpmyadmin in url bar but when connecting through C# coding it says,
Host 'pc1' is not allowed to connect to this MySQL server
Pc 1 is my pc on which i am coding.
please help me.

Enable Remote Root Access to MySql. click here for more details
Snippet taken from above:
create a new HOST for root and allow root to login from anywhere.
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;
mysql> exit

Related

C# code is unable to connect to Azure SQL database

I am trying to connect to a sample database I have created in Azure using C# (.NET Core 3.1)
I have enabled my IP address within Azure's Firewall rules.
I am able to use VS2019's SQL Server Object Explorer to connect and view the database within with no problems.
However, when I run a simple C# app on the same PC to execute a query to count the number of records in a table, it throws the following exception at the point where the connection is opened (conn.Open());
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: TCP Provider, error: 0 - The requested address is not valid in its context.)
The C# code;
using System;
using System.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = " Server=tcp:beaconsqlsql.database.windows.net,1433;Initial Catalog=MRP2;Persist Security Info=False;User ID=beaconadmin;Password=********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM [dbo].[Table]";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
I've tried temporarily turning off the firewall on my PC, but that made no difference.
The fact that SQL Server Object Explorer can connect but the C# code cannot makes it sound like there's a problem with the C# code, but I can't see any differences between it and the samples I've looked at.
I created one Azure SQL database and allowed my client IP like below :-
I created one .Net Console application and ran your code, I replaced
using System.Data.SqlClient
with
using Microsoft.Data.SqlClient
You can use any of the above packages.
Copied connection string from Azure Portal > Azure SQL server > Connection string refer below :-
C# Code:-
using System;
using System.Linq.Expressions;
using Microsoft.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=sqldbname;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT * FROM Products";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
Output :-
I tried to run the code with the connection string format you mentioned in the comments :-
Data Source=azuresqlservername.database.windows.net;Initial Catalog=databasename;User ID=siliconuser;Password=password;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And I was able to run the same code above and got the desired output:-
When I tried to change the Azure SQL server name in the connection string, I got the same error code as yours, refer below :-
Verify if your connection string has any syntax missing and validate it from Azure Portal.
I ended up taking a copy of the project home and running it on my home PC, and it worked correctly and reliably (after telling Azure to allow that IP address as well)
It turned out the answer was embarrassingly obvious - in addition to the standard Windows 10 firewall, my work PC is running another virus protection/firewall software, and that also needed to be told to allow the app thru.
Definitely one to remember for next time... Although I am kind of intrigued that on two occasions (once mentioned above, once afterwards) out of a few hundred attempts the app did manage to get thru and connect.
Thank you everyone for your answers and help.

Connecting Visual Studio to a SSH Tunneled MySQL Server

I was looking for a workaround for configuring my database connection.
I saw that opening 3306 port is dangerous and we should be using SSH Tunnel instead to connect to the database.
I configured my MySQL server using docker and successfully connected it using MySQL Workbench
Now I have to configure and connect it to Visual Studio 2022 to be able to query to the database.
Visual Studio 2022 is only supported by MySQL Data thru NuGet packages which doesn't have a gui connection setup.
I installed Visual Studio 2019 which is officially supported by MySQL Database and can be configured thru Data Source.
How can I setup MySQL Database connection to my Visual Studio if it's SSH Tunnel configured.
Add Connection window only shows basic information about the connection. I'm not sure how to configure this over a SSH Tunnel.
Thank you in advance.
For security reasons, sometimes the database server can only be accessed through SSH. For example, the MySql service is installed on server A, and machine A can only be accessed by machine B, and the deployment environment may be on machine C. In this case, C The server connects to the A server through the B server. At this time, SSH connection is required, and the SSH.NET class library is required:
code show as below:
using MySql.Data.MySqlClient;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SSHMySql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SSHConnectMySql();
}
public void SSHConnectMySql()
{
string SSHHost = "*.*.*.*"; // SSH address
int SSHPort = ; // SSH port
string SSHUser = "user"; // SSH username
string SSHPassword = "pwd"; // SSH password
string sqlIPA = "127.0.0.1";// Map addresses In fact, it is possible to write other MySql on Linux My.cnf bind-address can be set to 0.0.0.0 or not
string sqlHost = "192.168.1.20"; // The IP address of the machine installed by mysql can also be an intranet IP, for example: 192.168.1.20
uint sqlport = ; // Database port and mapping port
string sqlConn = "Database=mysql;Data Source=" + sqlIPA + ";Port=" + sqlport + ";User Id=user;Password=pwd;CharSet=utf8";
string sqlSELECT = "select * from user";
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHHost, SSHPort, SSHUser, SSHPassword);
connectionInfo.Timeout = TimeSpan.FromSeconds();
using (var client = new SshClient(connectionInfo))
{
try
{
client.Connect();
if (!client.IsConnected)
{
MessageBox.Show("SSH connect failed");
}
var portFwdL = new ForwardedPortLocal(sqlIPA, sqlport, sqlHost, sqlport); // map to local port
client.AddForwardedPort(portFwdL);
portFwdL.Start();
if (!client.IsConnected)
{
MessageBox.Show("port forwarding failed");
}
MySqlConnection conn = new MySqlConnection(sqlConn);
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.SelectCommand = new MySqlCommand(sqlSELECT, conn);
try
{
conn.Open();
DataSet ds = new DataSet();
myDataAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[];
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
conn.Close();
}
client.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
Note: If an error occurs, you can stop the MySql service on the local (development machine).
Required dll: SSHDLL.rar
You can fill in the following information to configure the connection to the MySql database.
Server name: Enter the IP address of MySQL, which is 127.0.0.1 as seen in your SSL connection information.
User name: Enter the user name of Mysql
Password: Enter the password of Mysql
Database name: Enter a test database
Hope it can help you

Host is not allowed to connect to this mysql database

I'm making a web api chat application in ASP.NET Razor Pages in VS Code with SignalR and with MySQL database. (Microsoft SQL Server Management Studio)
I wanted to store the messages and the users in a table, but when I made the MySQL connection I got an error message:
MySql.Data.MySqlClient.MySqlException (0x80004005): Host '' is not allowed to connect to this MySQL server
It can cause, that I connected to the database before in appsettings.json file with ConnectionString?
Here is the ChatHub.cs code:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
using System;
using MySql.Data;
using MySql.Data.MySqlClient;
using probagetrequest.Models;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
string connn = "Server=localhost;Database=DBChatApp;user id=sa;password=xxx";
MySqlConnection con = new MySqlConnection(connn);
try {
Console.WriteLine("Connecting to MySql...");
con.Open();
string cmddd = "INSERT INTO Messages (Username,Message) VALUES (#Usernamee,#Messagee)";
MySqlCommand cmd = new MySqlCommand(cmddd, con);
cmd.Parameters.Add("#Usernamee", MySqlDbType.VarString).Value = user;
cmd.Parameters.Add("#Messagee", MySqlDbType.VarString).Value = message;
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
}
con.Close();
Console.WriteLine("Done!!!!!");
Console.WriteLine($"user={user}, message={message}");
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Did you try logging into MySQL DB through mysql client CLI. I think it's a problem with "mysql user" privileges mentioned in your project to connect to the MySQL DB.
In general, the error you mentioned comes when a new database is setup but left un-configured.
Try the following commands logging into MySQL as super user
mysql> CREATE USER 'root'#'%' IDENTIFIED BY 'root';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' WITH GRANT OPTION;

Csharp windows application MySql connection

I cannot connect to MySql from my C# windows form application. I also have posted a question already in
invalid username/password
but got nothing solution.
Suppose my website name is www.google.com and cpanel user name is imrancpanel, my cpanel password is imranpd, I create a database imrandb, create a database user imrandbuser and check all permissions to this user for this website. whats the problem in this code?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace CSharpMySql
{
class Program
{
static string getString(string msg)
{
Console.Write(msg);
return Console.ReadLine();
}
static void Main(string[] args)
{
string myConnectionString = #"server=google.com;userid=imrancpanel_imrandbuser;
password=imranpd;database=imrandb";
MySqlConnection con = null;
MySqlDataReader reader = null;
string cretablestr = "CREATE TABLE IF NOT EXISTS AutoCaptchaTable (LoginID char(25), Password char(25), ActivationStatus char(25), NofTransactions int );"
try
{
//MySqlConnection
conn = new MySqlConnection(myConnectionString);
conn.Open();
MessageBox.Show("OK");
conn.Close();
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1042:
MessageBox.Show("Can't get hostname address. Check your internet connection. If does not solve, contact Administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
}
}
}
}
Most website hosters don't allow remote access to MySQL
only with localhost
you need to create a webservice with php to allow that or get an alternative
Enable remote access in cpanel by adding host(IP OR DOMIAN etc)

MySQL database to C# connection timeout

stackoverflow community! Once more, I come here seeking for your help...
My problem is: I have made a c# application used to register accounts in a MySQL database hosted by Byethost (SecureSignup). The connection works, but not all the time, even though no conditions are changed.
One minute I can submit the query and PhpMyAdmin shows it as beeing written in the database, but a few minutes later, when I try the exact same thing, I get various timeout errors ranging from "Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." to "Timeout IO Operation"... Here is my code, maybe having it could help you understand why it has such a strange behaviour from time to time, because I sure can't.
(I have granted my IP remote MySQL access from the cpanel, and the login data are 100% correct)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Main
{
public partial class Form1 : Form
{
string connString;
MySqlDataReader reader;
MySqlConnection conn;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********";
conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "INSERT into users (Username,password) VALUES('" + usr.Text + "','" + pass.Text + "')";
conn.Open();
int timeoutvalue = conn.ConnectionTimeout;
command.ExecuteNonQuery();
MessageBox.Show(timeoutvalue.ToString()); //This was a curiousity, it displays 15
conn.Close();
}
}
}
You should use parameters to prevent SQL injection.
Also use the using statement to properly dispose your MySQL objects.
private void button1_Click(object sender, EventArgs e)
{
connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********";
using (conn = new MySqlConnection(connString))
{
string query = "INSERT INTO users (Username, password) VALUES (#usr, #pass)";
// are you sure your column name is Username and not username ?
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(conn, query))
{
cmd.Parameters.AddWithValue("#usr", usr.Text);
cmd.Parameters.AddWithValue("#pass", pass.Text);
cmd.ExecuteNonQuery();
// No need to close your connection. The using statement will do that for you.
}
}
}
As for the connection problems, I think you should contact your host for answers. I use MySql all the time using C#, without any problems, so i think it's a problem with your hosting.

Categories

Resources