Connection failed with MySQL .NET Connector - c#

I cannot connect to MySQL it fails on line connection.Open(), is there something wrong with my code ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQLConnection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=localhost:3316;" +
"DATABASE=mydb;" +
"UID=user;" +
"PASSWORD=password;";
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
// ...
connection.Close();
}
}
}

this is the string format I use to connect via the MySql.Data.dll version 6.1.2.0
server={0};user id={1};password={2};database={3};port={4}
so your connection string should be
server=localhost;user id=user;password=password;database=mydb;port=3316

You need to specify the Port as a separate argument in the connection string and it looks like the password key is "Pwd" instead of "Password".
See connectionstrings.com for help on the exact syntax.

Related

Connection to mysql database does not work c #

I'm trying to connect to my mysql database (I'm hosted by infinityfree.net), entering these credentials:
connection = new MySqlConnection("Server=sql306.epizy.com; Port=3306; Database=epiz_27674946_db1; Uid=epiz_27674946; Pwd=**********; ");
But I get this exception:
Unable to connect to any of the specified mysql hosts
I don't know why this happens, the credentials should be right...
Can you help me?
Full code:
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;
using MySql.Data.MySqlClient;
namespace sharetru
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MySqlConnection connection;
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection = new MySqlConnection("Server=sql306.epizy.com; Port=3306; Database=epiz_27674946_db1; Uid=epiz_27674946; Pwd=*******; ");
connection.Open();
if (connection.State == ConnectionState.Open)
{
label1.Text = "Connected";
label1.ForeColor = Color.Green;
}
else
{
label1.Text = "Not Connected";
label1.ForeColor = Color.Red;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Regarding this service (infinityfree) it is not possible to access mysql from desktop applications (outside the infinityfree host)
https://support.infinityfree.net/mysql/how-to-connect-with-mysql/
The code looks correct. The issue probably is in the connection string details.
Are you able to connect using the following connection details via some GUI tool?
Workbench for example https://dev.mysql.com/downloads/workbench/

Is it an error in my class? MySql connection isn't working properly [Visual C#]

Okay, I'm trying to make a simple project for school, in which the teacher is letting us use the root user so we connect to databases everything. But while compiling, there seems to be an error in my class I use to connect to MySql:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
namespace BuscarDatos
{
class ClaseConectar
{
public static MySqlConnection obtener_conexion()
{
MySqlConnectionStringBuilder c = new MySqlConnectionStringBuilder();
c.Server = "localhost";
c.UserID = "root";
c.Password = "*******"; //password
c.Database = "proyecto_almacen"; //my database name already created
MySqlConnection con = new MySqlConnection();
con.Open();
return con;
}
}
}
I keep getting this error:
MySql.Data.MySqlClient.MySqlException: 'Authentication to host '' for user '' using method 'mysql_native_password' failed with message: Access denied for user ''#'xxxxxxxxxx' (using password: NO)'
Also, I changed it to MySqlConnection since I got an error before in another class, about how I couldn't convert MySql into Sql only. Here's an example of the class I changed it for:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace BuscarDatos
{
class Agregar
{
public static int AddName (string pNombre,string pAp_paterno, string pAp_materno, string pMatricula,
string pDireccion, string pTelefono)
{
int resultado = 0;
MySqlConnection con = ClaseConectar.obtener_conexion();
MySqlCommand Comando = new MySqlCommand(string.Format("Insert into maestros (nombre, ap_paterno, ap_materno, matricula," +
"direccion, telefono) values('{0}','{1}','{2}','{3}','{4}','{5}')", pNombre, pAp_paterno, pAp_materno,
pMatricula, pDireccion, pTelefono), con);
resultado = Comando.ExecuteNonQuery();
con.Close();
return resultado;
}
}
}
You're not giving the connection any connection string. It doesn't know what to open.
When you create the MysqlConnectionStringBuilder it is completely separate from the MySqlConnection you create. You must use them together:
MySqlConnection con = new MySqlConnection(c.ConnectionString);
This way you're actually giving the generated connection string to the connection object.

Code using wrong namespace

I having an aspx.cs file that I am adding code to. I have all the right namespaces and references in my solution, but my code is referencing the wrong namespace with the following error on my Server server = new Server()
System.Web.UI is a 'property' but used as a 'type'
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IISLoggingSolution
{
public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//connection string for SQL DB
string connectionString = #"Data Source=Computer\SQLEXPRESS;Initial Catalog=IISLogs;Integrated Security=True";
//Location of the query to be ran
string script = File.ReadAllText(#"C:\\Users\\User\\Desktop\\query.txt");
SqlConnection conn = new SqlConnection(connectionString);
//this is the error line
Server server = new Server(new ServerConnection(conn));
//executes query
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
How can I get it to use the Microsoft.SqlServer.Management.Smo instead of trying to used the System.Web.UI?
using NS_Server = Microsoft.SqlServer.Management.Common;
using System.Web.UI;
...
NS_Server.Server server = new NS_Server.Server();
the line using NS_Server is an alias. You can use it as a shortcut when there are namespace collisions.
You can use an alias directive:
using Server = Microsoft.SqlServer.Management...Server;
It may not work if property takes precedence, but in that cas you can simply specify the full namespade path.
var server = new Microsoft.SqlServer.Management....Server();

Simple C# connection to .accdb file

All I want to do is to retrieve data from tables in .accdb file.
Here is my full application:
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;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Microland.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("select CustID from Customers WHERE CustID = 1;", myConn);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
label1.Text = myReader.ToString();
}
myConn.Close();
}
}
}
I think I am missing some using at the very top or my code is somewhat broken becasue then I click the button1 the label1 text changes to System.Data.OleDb.OleDbDataReader.
Also is this the correct way to connect to access data base (.accdb) Do I need to do this walkthrough in order for it to work or this is irrelevant to what I need to do?
Thanks for any information! Very appreciated
When you call myReader.ToString() it returns a string that represents the current object. So "System.Data.OleDb.OleDbDataReader" is exactly that.
It seems like you want the label to be equal to the data that's read. I'm not familiar with this reader in particular, but refer here for documentation.
You'll need to call one of the Get*() functions.
label1.Text = myReader["CustID"] as string; // if nullable field
Or
label1.Text = (string)myReader["CustID"] // if not null

Can't able to connect to Database

I have installed the MySQL server using XAMMP.Created a new database with some data using phpmyadmin.Then i tried to connect to database using this code.But it did not connect.It shows me an error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Testing!");
SqlConnection myco = new SqlConnection("server=localhost;User Id=root;database=customer;Trusted_Connection=yes");
try
{
myco.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
}
}
Error:
http://pastebin.com/MyEtk4w6
You have MySql then you need to use the classes for MySql not the ones used for SqlServer
MySqlConnection myco = new MySqlConnection("Server=localhost;Database=customer;" +
"Uid=username;Pwd=password;");
Also the connection string for MySql is different
Server=localhost;Database=customer;Uid=username;Pwd=password;
The connection strings for MySql could be very numerous, you should check the correct one for your requirement here at connectionstrings.com
It's because you're using a SqlConnection object which is for Microsoft SQL Server.
Use a MySQLConnection instead.

Categories

Resources