Connect desktop c# application to online mySql databse - c#

I have a windows form application in C# and sometimes I want to push some data table from this application to an online mySql server which is hosting all data for my website in PHP. To do that I've installed :
1- MySql for visual studio version 1.2.3
2- MySql Connector.Net 6.9
Also, I have enabled Remote MySql on the server so I can make the connection. I used the '%' wildcard for the meantime because my IP address is dynamic.
my basic c# connection code is as below :
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "Server=*******;Database=*******;Uid=******;Pwd=********;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
MessageBox.Show("connected successfully..");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
Unfortunately, every time I run this code I am getting an error which says
"Unable to connect to any of the specified MySQL hosts".
I don't' know where the problem is. Is it something on the UNIX server which
blocks the connections or some other thing which I need to do. I am also new to the CPanel interface and how to deal with it.
I appreciate all the help provided.
Many Thanks.

http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
Did you see that? You can try it.

I know this is an old question but I had the same issue many years ago and the only way I could get it to work was to enable remote MySql on the server I was running. This basically means allowing remote connections to access the DB. This of course is very risky and poses a major security problem. You can limit connections from specific IPs, but in my opinion its best to have a local DB and then perhaps push updates to an online source somehow.

Related

"Unable to connect to any of the specified MySQL hosts" in UWP app (C#)

I'm trying to connect a UWP app written in C# to a MySQL DB hosted on another machine on the local network (it's on a Raspberry Pi, but I doubt that makes a difference). The code I have right now is:
string M_str_sqlcon = "Server=192.168.0.101;Port=3306;Database=****;User ID=****;Password=****;";
MySqlConnection mysqlcon = new MySqlConnection(M_str_sqlcon);
MySqlCommand mysqlcom = new MySqlCommand("select * from mysql.users", mysqlcon);
mysqlcon.Open();
However, the code fails with a 'Unable to connect to any of the specified MySQL hosts.' error. Here's the pic of the error pop-up.
I've tried changing the server address, and if I enter one that isn't present on the local network, it fails with a different error (along the lines of Unable to connect to any of the specified MySQL hosts, cannot reach target server).
I've tried various connection strings I've found around StackOverflow, and in MS' own docs, but nothing seems to help.
I can properly ping the DB IP from the machine I'm developing this app on, and I can access the database normally using MySQL Workbench, so I'm sure it isn't a problem with the user permissions/settings.
Any help would be appreciated!
Try to connect with the database using some GUI tools. If it works you will be sure that there is a problem with your application. It could be network problems etc.

How to connect remotely to MySQL server

What is the best way to connect remotely to MySQL server on domain ?
I want to make an desktop app or maybe it is easier to do it with asp.net ?
Use Mysql Workbench for desktop use to connect to Mysql Server.
For coding: Get Mysql client library for .net . It's called mysql connector. Add
using Mysql.Data; namespace
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html
Makes no difference what kind of application you are creating.
your code will look very similar like this one:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
1- I usually use HeidiSQL tool to connect to MYSQL server otherwise on localhost or remotely servers on CPanels.
most of CPanels allow to remote connection by adding % at access hosts field to enable me connect remotely anywhere.
from your cpanel go to the database tools then -> you will find link for Remote mysql -> then you can any IP address to make server allow to connect, if you want connect anywhere you put %.
Note: CPanels are little different each others.
2- if you want connect to mysql in your code, you make a normal connection after doing step 1.

How to Connect to Remote MySQL Server with my C# Application

I need to connect my C# application developed in my Standalone PC with my Hosted Linuux MySQL Server. How can i do it.. Is there any server configuration setup or any kind of Remote Connection Permission Setting have to be done? Please help with this..
Make sure that the server where MySQL is at can accept connections.
Read this to read how to configure your c# application to connect to MySQL.
The connection string code should like this
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
You need to allow the remote connection by this way
Mysql has very good documentation how to connect mysql server (local and remote).
It is here http://dev.mysql.com/doc/index-connectors.html
And your case may be this http://dev.mysql.com/doc/connector-c/en/index.html
Its Pretty Simple to Implement
1) Download My Sql Connector From https://dev.mysql.com/downloads/connector/net/6.9.html
2) In your C# Project add refrence of Mysql.Data.Dll
3) use this Connection String
string connectionString= "SERVER=000.000.000.000;DATABASE=testdb;UID=test;PASSWORD=test123;"
4) use same like this sample code
MySqlConnection conn = new MySqlConnection(connectionString);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
// Perform database operations
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
or Read this tutorials
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-connection.html

connect to database c#

I'm trying to connect to a DB on a server using C# but with no luck.
I tried using this:
public static string m_ConnectionString =
#"Network Library=dbmssocn; Data Source=*server ip*,*port*; database=*db name*; " +
#"User id=*db username*; Password=*db pass*;";
public static SqlConnection myConnection = new SqlConnection(m_ConnectionString);
I get this error:
Connection Timeout Expired. The timeout period elapsed while
attempting to consume the pre-login handshake acknowledgement. This
could be because the pre-login handshake failed or the server was
unable to respond back in time. The duration spent while attempting
to connect to this server was - [Pre-Login] initialization=9343;
handshake=5654;
when I used myConnection.Open();
I tried also to set the timeout to int.MaxValue and it didn't work.
A very good source for SQL Server (and many other) connection strings is http://www.connectionstrings.com/sql-server/. Depending whether you are connecting through ODBC, OLE DB or Native Client, you have to choose another connection string.
Try
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
or
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
There are a lot of options to choose from, depending on the exact SQL Server version, the security type and many more.
UPDATE
First you have to choose a data access technology.
.NET Framework Data Provider for SQL Server (SqlConnection), Is the preferred way of accessing the SQL Server from .NET code. (See When to use the SQL Native Client for a comparison)
Native Client: Is a very fast way of accessing the SQL Server and supports the new features, as it accesses the SQL Server TDS protocol directly and works for non .NET code. It should be preferred for non .NET code.
ODBC: Is relatively fast and compatible to a lot of different databases. Choose this one if the data base type might change in future or if you are accessing "exotic" databases.
OLEDB: For SQL Server it is relatively slow and will be depreciated by Microsoft.
Then you have to choose between SQL Server Authentication (User/Password) and Windows Authentication. I would choose the latter if possible. With Windows Authentication the SQL-Server assumes that if you logged in successfully to Windows you are a trusted user. The Windows user name will then be mapped 1 to 1 to a SQL-Server user. Of course this user then must still have been granted the rights requested for the operations that he will perform on the SQL Server (like SELECT, INSERT, UPDATE, DELETE). If the DBA didn't install Windows Authentication, you will have to go with uid/pwd.
This worked for me:
string connectionString =
"Data Source=192.168.123.45;Initial Catalog=MyDatabase;Integrated Security=SSPI;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
using (SqlCommand command = new SqlCommand(
"SELECT Region FROM dbo.tlkpRegion WHERE RegionID=30", connection)) {
connection.Open();
string result = (string)command.ExecuteScalar();
MessageBox.Show("Region = " + result);
}
}
I think that Data Source=*server ip*,*port*; should be Data Source=*server ip*:*port*;, replacing , with :. But if the port is not specific, I don't think you really need it. Also you're not defining a driver, I don't know it this works without it.
Also a advice: look up LINQ to SQL or ADO.NET Entity Data Model. Those can really simplify use of databases and using LINQ you can write a query inside code which is a lot similar to sql and Visual Studio also helps with intellisense so you don't have to remember all table and column names.

SQL Server Connection Timeout C#

First off I'd like to let everyone know I have searched my particular problem and can't seem to find what's causing my problem.
I have an SQL Server 2008 instance running on a network machine and a client I have written connecting to it.
To connect I have a small segment of code that establishes a connection to an sql server 2008 instance and returns a DataTable populated with the results of whatever query I run against the server, all pretty standard stuff really. Anyway the issue is, whenever I open my program and call this method, upon the first call to my method, regardless as to what I've set my Connection Timeout value as in the connection string, it takes about 15 seconds and then times out. Bizarrely though the second or third call I make to the method will work without a problem.
I have opened up the ports for SQL Server on the server machine as outlined in this article: How to Open firewall ports for SQL Server and verified that it is correctly configured. Can anyone see a particular problem in my code?
string _connectionString = "Server=" + #Properties.Settings.Default.sqlServer + "; Initial Catalog=" + #Properties.Settings.Default.sqlInitialCatalog +
";User Id=" + #Properties.Settings.Default.sqlUsername + ";Password=" + #Properties.Settings.Default.sqlPassword + "; Connection Timeout=1";
private DataTable ExecuteSqlStatement(string command)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
using (SqlDataAdapter adaptor = new SqlDataAdapter(command, conn))
{
DataTable table = new DataTable();
adaptor.Fill(table);
return table;
}
}
catch (SqlException e)
{
throw e;
}
}
}
The SqlException that is caught at my catch is : "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
This occurs at the conn.Open(); line in the code snippet I have included. If anyone has any ideas that'd be great!
Addendum If I ping the server it's <10ms response time. Additionally I'm getting the same behavior when using SQL Server Management studio (I've just tried this after writing this question as the thought just crossed my mind). I would presume that this has to be a network issue as opposed to a code issue as it also takes two attempts when using SQL Server Management studio. I realise I can implement an error check for connection failure and then re-attempt the connection (I should probably do this anyway) but this doesn't seem particularly 'clean' to me as it doesn't address the underlying problem. Does anyone here have any experience with this issue?
Edit
Although over a year later this question has been viewed over 4000 times, I've since discovered that although I /thought/ the firewall ports were opened, they actually weren't. I'd incorrectly assumed that you need to open the firewall in Windows to the port number that SQL Server uses, in my case I set it to allow connections on TCP port 1433, the firewall caused issues when attempting to establish an initial connection.
I discovered that the correct way to set it up was to set Windows Firewall to allow the SQL Server Instance executable through. To do this you need Add a Program in Windows Firewall, browse to the folder your sql instance resides in such as C:\Program Files (x86)\Microsoft SQL Server\MSSQL10_50.SQLINSTANCE\MSSQL\Binn and then add the sqlservr.exe file to the firewall rules.
You are setting the connection timeout value to 1 second. Drop it from connection string and try again.
Or the problem could be with the SQL select you are using. Could it be taking a long time. If so, the 2nd and 3rd calls would retrieve the cached values and thus run much quicker.

Categories