Cannot connect to MySQL Server and have no idea why [duplicate] - c#

This question already has answers here:
ASP.NET use SqlConnection connect MySQL
(3 answers)
Closed 2 years ago.
I am trying to connect to MySQL server
Screenshot from MySQL Workbench:
using System;
using System.Data.SqlClient;
namespace C_sharp_test
{
class Program
{
static void Main(string[] args)
{
try
{
string connectionString = "server=localhost;uid=root;pwd=***********;database=terra_incognita_online";
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = connectionString;
sqlConnection.Open();
Console.WriteLine("open");
sqlConnection.Close();
Console.WriteLine("close");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
I get this error
System.Data.SqlClient.SqlException (0x80131904): 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I have no idea what to do, please help

Replace "SqlConnection" with "MySqlConnection" and that will work.
namespace C_sharp_test
{
class Program
{
static void Main(string[] args)
{
try
{
string connectionString = "server=localhost;uid=root;pwd=***********;database=terra_incognita_online";
MySqlConnection sqlConnection = new MySqlConnection();
sqlConnection.ConnectionString = connectionString;
sqlConnection.Open();
Console.WriteLine("open");
sqlConnection.Close();
Console.WriteLine("close");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
Also, Install nuget package MySql.Data;
And Add Reference
using MySql.Data.MySqlClient;

You are trying to connect to a MySQL database server with classes intended for SQL Server. They use different protocols, so that doesn't work (and almost certainly never will).
Have a look at the MySQL connector for .NET, if you want to use MySQL rather than SQL Server.

Related

How to fix network related errors in visual studio when i tried to connect to database

when i tried to run this program in visual studio 2010 its shows an error. Like this "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:Named pipes Provider,error:40-could not open a connection to SQL Server)"
public partial class tcregistration : Form
{
SqlConnection conn = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Users/dce 3/documents/visual studio 2010/Projects/TC_Maker/TC_Maker/TC_REG.mdf;Integrated Security=True;User Instance=True");
public tcregistration()
{
InitializeComponent();
}
private void insert_Click(object sender, EventArgs e)
{
string gender = string.Empty;
if (rbmale.Checked)
{
gender = "M";
}
else if (rbfemale.Checked)
{
gender = "F";
}
string tcrecieved = string.Empty;
if (rbyes.Checked)
{
tcrecieved = "Y";
}
else if (rbno.Checked)
{
tcrecieved = "N";
}
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmd = new SqlCommand ("TCAddorUpdate",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mode","Add");
cmd.Parameters.AddWithValue("#tcnumber",txttcno.Text.Trim());
cmd.Parameters.AddWithValue("#name",txtname.Text.Trim());
cmd.Parameters.AddWithValue("#dob",dtpdob);
cmd.Parameters.AddWithValue("#religion",txtrelig.Text.Trim());
cmd.Parameters.AddWithValue("#caste",txtcaste.Text.Trim());
cmd.Parameters.AddWithValue("#sex",gender);
cmd.Parameters.AddWithValue("#doa",dtpdoa);
cmd.Parameters.AddWithValue("#regno",txtregno.Text.Trim());
cmd.Parameters.AddWithValue("#dor",dtpdor);
cmd.Parameters.AddWithValue("#dept",txtdept.Text.Trim());
cmd.Parameters.AddWithValue("#sem", combosem);
cmd.Parameters.AddWithValue("#ifqulify",txtqualified.Text.Trim());
cmd.Parameters.AddWithValue("#conduct",txtconduct.Text.Trim());
cmd.Parameters.AddWithValue("#applieddate",dtpdoapp);
cmd.Parameters.AddWithValue("#ifrecieved",tcrecieved);
cmd.Parameters.AddWithValue("#receiveddate",dtpdor);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error Message");
}
finally
{
conn.Close();
}
}
}
}
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:Named pipes Provider,error:40-could not open a connection to SQL Server)
This is not a programming Problem, but a networking/connection string one.
Connection Strings are their own area of experetise, way outside the normal programmers knowledge. Luckily there is a page for it: https://www.connectionstrings.com/sql-server/
It turns out even when attaching, you have to supply a database name: "Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection."
And as others mentioned, you got the wrong kind of slashes too.
Pretty off topic, but exception handling is a pet peeve of mine. And yours has some of the serioues mistakes. Like catching exception and only exposing the message. Those are 2 Cardinal sins. Thee are two article on the thematic I link often:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

How to make a connection with MySql database from my CPanel with Visual Studio 2017

I am trying to make a connection to MySQL database from my cpanel with Visual studio, but I keep getting an error:
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: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I have installed both MySql for Visual studio and Connector/net. I have tried with both Server Explorer and through the code using the connection string. I have added my ip to the access host list on Remote MySql in CPanel. But nothing worked.
namespace Program
{
public partial class WebForm1 : System.Web.UI.Page
{
string connectionString = #"SERVER=mydomain.net;DATABASE=mydatabasename;UID=myuser;PASSWORD=mypass";
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown(DropDownList1);
}
public void FillDropDown(DropDownList dropDown)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCmd = new SqlCommand("Select * from MyTable", sqlCon);
sqlCon.Open();
dropDown.DataSource = sqlCmd.ExecuteReader();
dropDown.DataBind();
dropDown.DataTextField = "Name";
dropDown.DataValueField = "Id";
}
}
catch(Exception ex)
{
lblError.Text = ex.Message;
}
}
}
}
The SqlConnection-object may only be used for connections to MS-SqlServers. You have to use MySqlConnection to connect to MySql-server. This also applies to the SqlCommand.
Furthermore the used connection-string is not valid for MySql ('Password' should be 'Pwd') Compare your string to https://www.connectionstrings.com/mysql/

Very Simple C# program won't connect to Azure SQL Database

I am trying to write a very simple C# Script that establishes a connection to my Azure SQL Database.
using System;
using System.Data.SqlClient;
namespace first_project
{
class MainClass
{
public static void Main(string[] args)
{
var cb = new SqlConnectionStringBuilder();
cb.DataSource = "server.bloo.blah.foobar";
cb.UserID = "user#database";
cb.Password = "secret";
cb.InitialCatalog = "database";
using (SqlConnection connection = new SqlConnection(cb.ConnectionString))
{
try
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
From what I have gathered online, this code should be working? However, I am getting the following error
System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block. ---> System.Net.Sockets.SocketException: Operation on non-blocking socket would block
Could anyone enlighten me on what is going on? Thanks in advance.
First the SQL database has a firewall. You have to add your IP through the azure portal.
Secondly make sure your connection string is correct you can look at another sample online. I remember having syntax errors as well, just copy the string that azure gives you.
In your connection, instead of
cb.UserID = "user#database"
use
cb.UserID = "user"
That should work.

Database Connectivity with oracle database using c#

While trying to connect the oracle database I am getting the following error
"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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}
Problem may be silly one but this is my first time with database so need help:
My code is:
static void Main(string[] args)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=ORCL_BOA; database=BOANEWDOC;User Id=BOANEWDOC;Password=BOANEWDOC;Trusted_Connection=true";
conn.Open();
//code
}
you may need to reference Oracle.ManagedDataAccess.dll on ODTwithODAC121012.zip you can download from oracle site.
do not use System.Data.OracleClient as it is obsolete.
var connection = new OracleConnection(YourConnectionString);
try
{
connection.Open();
//AMK: Do some stuff with the db
}
catch (Exception exception)
{
//AMK: do some other stuff in case of error
}
finally
{
if(connection !=null && connection.State==ConnectionState.Open)
connection.Close();
}

Connect to SQL using OleDbConnection failing

I'm connecting to a remote SQL database using the OleDbConnection but it's failing.
var connection = new OleDbConnection
{
ConnectionString = "Provider=SQLOLEDB;server=MyRemoteIPAddress;Initial Catalog=MyDatabase;User ID=sa;Password=MyPassword"
};
try
{
connection.Open();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
The error I am getting is : [DBNETLIB][ConnectionOpen (Invalid Instance()).]Invalid connection.
However if I connect using SqlConnection, it connects ok.
var testConnection = new SqlConnection
{
ConnectionString = "server=MyIPAddress;database=MYDatabase;user id=MyUser;pwd=MyPassword"
};
try
{
testConnection.Open();
testConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Why can i connect via SqlConnection and not OleDbConnection?
The environment is not clustered but explicitly specifying the port fixed the issue.
This worked :
"Provider=SQLOLEDB;server=MyRemoteIPAddress,1433;Initial Catalog=MyDatabase;User ID=sa;Password=MyPassword"
Try using a server side code which does all the required functions. so that your application does not directly talk with the remote database. Ping me for further assistance.
you should specify the port 1433 when using OLEDB
Provider=SQLOLEDB;server=MyRemoteIPAddress,1433;Initial
Catalog=MyDatabase;User ID=sa;Password=MyPassword;

Categories