Has ping to MySQL Server, but fails to connect through C# code - c#

I'm using a C# program to connect to a database and display data in a grid (TableFromMySql).
I installed my program on a PC that sits on the same network as the database. Ping is okay, but my program fails to connect, it reaches the catch statement and shows me "No connection to DB" error.
private void SQLMethod(string query)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (MySqlCommand cmdSel = new MySqlCommand(query, connection))
{
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmdSel);
da.Fill(dt);
TableFromMySql = dt.DefaultView;
if (TableFromMySql.Count == 0)
System.Windows.MessageBox.Show("No results.", "INFO", MessageBoxButton.OK, MessageBoxImage.Error);
}
connection.Close();
}
}
catch
{
System.Windows.MessageBox.Show("No connection to " + serverIP, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Connection string is a string value:
private const string connectionString =
"SERVER=IP;" +
"PORT=3306;" +
"DATABASE=db;" +
"UID=root;" +
"PASSWORD=password;";
A few notes:
IP is the actual ip address of the DB, can't post it.
Connecting to the DB using HeidiSQL from that PC works fine.
I also checked the same code on my local PC with an Ubuntu VM running MySQL Server docker container and the code worked.
To create the installation file I used the Visual Studio Installer extension.
Any ideas?

So after a long time I found the answer. I added to the connection string "SslMode=None" and the problem was solved.

Related

MySQL port forwading in SSH.NET - An attempt was made to access a socket in a way forbidden by its access permissions

Installed Plesk on my VS. After this I can't setup SSH-tunnel to get data from other server-database. Using SSH.NET with below code. (This code works locally). Configured to allow communication for port 3306 in Plesk firewall. Any suggestions on how to solve this issue?
Error:
[SocketException (0x271d): An attempt was made to access a socket in a
way forbidden by its access permissions]
Code:
DataTable dt = new DataTable();
string IP = "ssh.xxxxxxxx.xxx";
string Username = "xxxxxxxxxx";
string password = "xxxxxxxxxx";
var connInfo = new Renci.SshNet.PasswordConnectionInfo(IP, Username, password);
using (var sshClient = new Renci.SshNet.SshClient(connInfo))
{
sshClient.Connect();
if (sshClient.IsConnected)
{
Renci.SshNet.ForwardedPortLocal port =
new Renci.SshNet.ForwardedPortLocal("127.0.0.1", 3306, "xxxxxxxx", 3306);
sshClient.AddForwardedPort(port);
port.Start();
using (MySqlConnection con = new MySqlConnection("SERVER=127.0.0.1;PORT=3306;UID=xxxxxx;PASSWORD=xxxxxxx;DATABASE=xxxxxxx; convert zero datetime=True"))
{
string tmpsql = "Select fname,lname,username FROM tbluser Where id=#id";
using (MySqlCommand cmd = new MySqlCommand(tmpsql, con))
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("id", MySqlDbType.Int16).Value = UserID;
da.Fill(dt);
}
}
}
sshClient.Disconnect();
}
The local port which you are trying to forward is most probably already used by another application (like a local MySQL database server).
Use another port. Or even better, let the system pick any free local port:
var port = new ForwardedPortLocal("127.0.0.1", "dbserver.example.com", 3306);
client.AddForwardedPort(port);
port.Start();
var connectionString =
$"SERVER={port.BoundHost};PORT={port.BoundPort};" +
"UID=xxxxxx;PASSWORD=xxxxxxx;DATABASE=xxxxxxx; convert zero datetime=True";
using (MySqlConnection con = new MySqlConnection(connectionString))
{
// ...
}
Related: C# SSH tunnel Postgres database connection

File Not Found Exception was unhandled in the line of adapter.Fill(table)

Im trying to connect to the database MySql but this error was appeared
FileNotFoundException was unhandled
in the line of adapter.Fill.
FileNotFoundException was unhandled Could not load file or assembly 'Renci.SshNet, Version=2016.1.0.0, Culture=neutral, PublicKeyToken=1cee9f8bde3db106' or one of its dependencies. The system cannot find the file specified
class CONNECT
{
private MySqlConnection connection = new MySqlConnection("Datasource=localhost;Port=3306;Username=root;Password=;Database=Csharp_Hotel_DB");
//create a function to return our connection
public MySqlConnection getConnection()
{
return connection;
}
//create a function to open the connection
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
//create a function to close the connection
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
private void buttonLogin_Click(object sender, EventArgs e)
{
CONNECT conn = new CONNECT();
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand();
String query = "SELECT * FROM `users` WHERE `username`=#usn AND `password`=#pass";
command.CommandText = query;
command.Connection = conn.getConnection();
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = textBoxUsername.Text;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = textBoxPassword.Text;
adapter.SelectCommand = command;
adapter.Fill(table); //this line is the FileNotFoundException was unhandled
// if the username and the password exists
if (table.Rows.Count > 0)
{
this.Hide();
MessageBox.Show("YES");
Main_Form mform = new Main_Form();
mform.Show();
}
else
{
if (textBoxUsername.Text.Trim().Equals(""))
{
MessageBox.Show("Enter Your Username to Login", "Empty Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (textBoxPassword.Text.Trim().Equals(""))
{
MessageBox.Show("Enter Your Password to Login", "Empty Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password Doesn't Exists", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
It's now working c.
Using the MySQL-connector-net-6.3.5 can fix this error or problem because I'm using .net 4
Thank you for your help.
it seems that you do not handle the exceptions adapter.fill could through.
use:
try{
adapter.Fill(table);
} catch(FileNotFoundException e) {
do stuff with e or your code
}
alternatively check the pathes if they exist before using them.
You are creating a data table without passing a name into the constructor. This means that the table is nameless and so when you try to call Fill on a nameless table you get your file not found exception.
You should pass in the table name
DataTable table = new DataTable("users");
This is a bug in MySQL Connector/NET, bug 96614. It will be fixed in Connector/NET 8.0.18.
Fixed as of the upcoming MySQL Connector/NET 8.0.18 release, and here's the changelog entry:
The Renci.SshNet.dll deployment was problematic for Connector/NET 8.0.17
MSI installations. Some applications, such as Microsoft Excel, were unable
to read MySQL data as a result. This fix removes unnecessary dependencies
on the DLL and also ensures that the MSI installation deploys the correct
Renci.SshNet.dll to the GAC.
A workaround you can use today is switching to MySqlConnector, an alternative OSS ADO.NET library for MySQL, which doesn't have this bug.

When running my application, SqlAdapter returns no data, when I'm running a stored procedure

It looks like it connects fine and does everything except returning data or displaying it on the datagridview. I'm not sure what exactly is wrong with this. It runs fine on the local machine if I run it in SQL Server Management Studio.
It doesn't seem to run correctly here though, its just a button that I'm clicking but nothing comes back to me.
SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand StoredProcedureCommand = new SqlCommand("storedprocedure", conn);
StoredProcedureCommand.CommandType = CommandType.StoredProcedure;
SqlParameter myParam1 = StoredProcedureCommand.Parameters.Add("#p1", SqlDbType.VarChar, 20);
myParam1.Value = "Arg";
SqlParameter myParam2 = StoredProcedureCommand.Parameters.Add("#p2", SqlDbType.VarChar, 300);
myParam2.Value = "Gra";
try
{
conn.Open();
MessageBox.Show("Database Connection Success");
}
catch (Exception conerr)
{
MessageBox.Show("Database Connection Failed");
}
try
{
StoredProcedureCommand.ExecuteNonQuery();
MessageBox.Show("Running stored procedure succeeded");
}
catch (Exception proerr)
{
MessageBox.Show("Running stored procedure failed");
}
try
{
using (SqlDataAdapter adap = new SqlDataAdapter(StoredProcedureCommand))
{
DataTable dt = new DataTable();
int rowCount = dt.Rows.Count;
adap.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Data returned fine" + " This many rows were returned" + rowCount.ToString());
}
}
catch (Exception erradapt)
{
MessageBox.Show("Error retrieving data to grid" + erradapt.ToString());
}
try
{
conn.Close();
MessageBox.Show("Closing database connection");
}
catch (Exception errclose)
{
MessageBox.Show("Error closing database connection");
}
I just noticed that your rowCount variable will always be 0 because it was assigned to before dt was filled. If you were using the rowCount for any kind of loop, the loop would just exit immediately. And your message will always say "This many rows came back 0".
Btw, I have used a similar piece of code in my application and it does work.
Thanks all for the help the problem was the connection string after going back to the stored procedure I noticed it
Thanks all for the help!!

Connecting C# to MYSQL database?

So i been trying to connect C# windows from to MYSQL database, i tryed many different methods that i found online but none seems to be working. here is my code please help (keep in mind this is the first time i use database before).
Here is the connecting class
class DbConnect
{
public static void DBConnect()
{
string connstr =
"server=localhost;user=root;database=login;port=3306;password=Password";
MySqlConnection conn = new MySqlConnection(connstr);
try
{
conn.Open();
}
catch
{
Console.WriteLine("went rong");
}
}
}
Here is the windows form im using
private void btnenter_Click(object sender, EventArgs e)
{
DbConnect.DBConnect();
MySqlCommand query = new MySqlCommand("INSERT INTO logininfo (username,
password) VALUES(#username, #password");
try
{
query.Parameters.AddWithValue("#username", txtusername.Text);
query.ExecuteNonQuery();
MessageBox.Show("S");
}
catch (Exception )
{
MessageBox.Show("something went wrong");
}
finally
{
DbConnect.DBClose();
}
}
User is passed in MySQL connection string using Uid. So your connection string should be like:
"server=localhost;Uid=root;database=login;port=3306;password=tro63jans";
You may see: MySQL connection string.
You should also catch exception in some object, so that you can get the details about the exception. Currently you are not showing any useful message from your exception.
catch (Exception ex) //at least
{
MessageBox.Show("something went wrong: " + ex.ToString());
}
One problem you have here is you're not setting the Connection property of your MysqlCommand to the MySqlConnection you're making earlier.
Change DBConnect() to return your MySqlConnection.
Set your MySqlCommand's Connection property to the returned value.
PSEUDO-CODE
MySqlConnection conn = DBConnect.DBConnect();
MySqlCommand command = new MySqlCommand(commandStr, conn);
command.ExecuteNonQuery();
conn.Close();

cannot connect to oracle server from C#.net application

I'm trying to connect to remote Oracle server. My connection string -
OdbcConnection con = new OdbcConnection();
con.ConnectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
I encountered error saying - "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" (System.Data.Odbc.OdbcException) Exception Message = "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified", Exception Type = "System.Data.Odbc.OdbcException", Exception WinRT Data = ""
I specified my connection string according to my TNSNAMES.ora
Entry for my DB in TNSNAMES.ora goes like this:
DB.WORLD=
(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST= xxxx)
(PORT=xxxxx)
)
(CONNECT_DATA=
(SERVER=dedicated)
(SERVICE_NAME=abc.domain.com)
)
)
Can someone explain on the error. Please help/suggest if my connection string went wrong and how to connect to Oracle server from my windows application
first install odp.net.managed using nuget packet manager:
Install-Package odp.net.managed
odp.net.managed work without preinstalled Oracle Client
next:
const string connectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
if you have tnsnames.ora in application folder:
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
or if tnsnames.ora in other folder:
Environment.SetEnvironmentVariable("TNS_ADMIN", #"path_to_tnsadmin.ora");
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
you need to use OracleConnection
OracleConnection conn = new OracleConnection(connectionString);
download and install Oracle Data Provider for .NET
Go to Connections Strings for Oracle
Maybe will find some help
Use following Code:
using System;
using Oracle.DataAccess.Client;
class ConnectionSample
{
static void Main()
{
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=oracle";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");
}
}
Source ONE , TWO and THREE
Try something like this class :
public class OracleOperations
{
OracleConnection oraConn = new OracleConnection();
private bool connStatus;
public OracleOperations()
{
connStatus = false;
connect();
}
~OracleOperations()
{
disconnect();
}
public bool getConnStatus()
{
return connStatus;
}
public void connect()
{
string connString = "User Id=xxxx; Password=yyyyy; Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.10)(PORT=1583))(CONNECT_DATA=(SERVER=dedicated)(SID=oracledb)))";
if (oraConn.State != ConnectionState.Open)
{
try
{
oraConn.ConnectionString = connString;
oraConn.Open();
Console.WriteLine("Successful Connection");
connStatus = true;
}
catch (Exception eOra)
{
Console.WriteLine(eOra.Message+ "Exception Caught");
connStatus = false;
throw eOra;
}
}
}
public void disconnect()
{
if (oraConn.State == ConnectionState.Open)
{
try
{
oraConn.Close();
connStatus = false;
Console.WriteLine("Connection Closed");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "Exception Caught");
}
}
}
}
I would try Tnsping utility to make sure you can connect via tnsnames.ora
Try putting tnsnames.ora and sqlnet.ora in the same folder of the application and see if that addresses the issue.
With Managed ODP.Net there is one catch it does not support LDAP look up (e.g. LDAP.ora)
I'Ve Created an app.config File and configured the DB entry like this
<configuration>
<configSections>
<section name ="Environment" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Environment>
<add key ="CIT" value ="Password=pwd123;User ID=abc123;Data Source=db1;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="SIT" value ="Password=pwd234;User ID=abc234;Data Source=db2;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="UAT" value ="Password=pwd345;User ID=abc345;Data Source=db3;Persist Security Info=True;Provider=MSDAORA"/>
</Environment>
</configuration>
Reffered that configuration into my form using ConfigurationManager(Need to refer the assembly - system.configuration). Add namespace - using System.Collections.Specialized to avail NameValueCollection. Code goes like this
environments = ConfigurationManager.GetSection("Environment") as NameValueCollection;
string strConnString = environments[envs];
conn = new OleDbConnection(strConnString);
conn.Open();
OleDbDataAdapter objDa = new OleDbDataAdapter("select * from tblABC", conn);
DataSet ds1 = new DataSet();
objDa.Fill(ds1); dataGridView1.DataSource = ds1.Tables[0];
Using datset, i've populated datagrid using an OleDbDataAdapter. It worked for my Windowsapplication.

Categories