Connect C# to Mysql database - c#

I want to connect to mysql server from C#. I found some code on the net but somewhere there is something wrong because i get
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
error.
private void Initialise()
{
server = "dns to server";
database = "db_name";
uid = "root";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" +
uid + ";" + "PASSWORD=" + password + ";";
OR
connectionString = "Server=xxx.no-ip.org;Database=rdb;"+
"Uid=root;Pwd=wHt2%Zt;";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
Console.Out.Write("SUCCESS");
else
Console.Out.Write("ERROR");
}
private bool OpenConnection() {
try {
connection.Open();
return true;
}
catch (MySqlException ex){
switch (ex.Number) {
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
I don't get any message on the console. I added Mysql.Data as a reference to my project and i used using MySql.Data.MySqlClient;
I also tried connectig through gui but with no luck. Ideas ?
Edit 1 : with either connection string my program is still not working.
Edit 2 : OpenConnection method added.
Edit 3 : This is the error i get !

p.s.
http://www.connectionstrings.com/mysql
probably you need to change your approach...use a webconfig or app config to setup and read your connectionstrings from the config...
I would also recommend you to read this...
http://www.codeproject.com/Articles/12300/An-ASP-NET-Application-Using-a-MySQL-Database
UPDATE
Based on your updated findings...there can be two problems, first double check your connectionstring, Second is to check if the user "root" has the required permissions.

Look here: http://www.connectionstrings.com/mysql
Have all.

Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
I think the problem is your database server:
Server=xxx.no-ip.org
It seems your app doesn't find the server. Check firewall.
You can debug and set an interruption point and check which exception it's throwing, not just the number

Related

How to save data to database using retrieved ID from datagridview?

I wanted to insert some data to the mysql database using that ID that I have retrieved from datagridview. i am new in programming. can someone please help me? thanks
First you need to download and intall
MySQL ADO.Net connector
it's the official ado.net connector for C# applications. once you intall that you can use ado.net standered data access methods to save data.
basic steps
First create a connection to the my sql data base.
Then create a command object contains the insert command.
then provide the object that contain the so called ID and finalize the command object
then Execute the command against the database.
Sample code
This is the class variables that will be used later
private MySqlConnection connection; // this MySqlConnection class comes with the connector
private string server;
private string database;
private string uid;
private string password;
This will Initialize method will configure the connection with the configuration data
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
this method will open a connection to the database . you should write a C Lose method as well .because it's best practice to always close the connection after you used it
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
This will insert a record to database . query will contains the T-SQL query that runs against the database
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
Hope this will help

C# Mysql connection working only on localhost

I'm connecting to a mysql database in c#, and it all works well as long as I input the server address as "localhost" or its ip, but if I try a remote ip it fails with:
Error: 0 : Unable to connect to any of the specified MySQL hosts.
here's the code:
server = Properties.Settings.Default.DBHost;
port = Properties.Settings.Default.DBPort;
database = Properties.Settings.Default.DBName ;
uid = Properties.Settings.Default.DBUser;
password = Properties.Settings.Default.DBPassword ;
string connectionString;
connectionString = "SERVER=" + server + ";" + "PORT=" + port + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
[...]
if (this.OpenConnection() == true){
// exec db operations
}
else{
MessageBox.Show("Database Connection Error.");
}
Tested:
No firewall restrictions
Same error in different computers
Already tried on with different remote databases, all with set privileges and accessible from other sources
If its your mysql server then,
Check you port is open or not. (probably 3306)
Change your bind-address in your my.ini file (from 127.0.0.1 to 0.0.0.0)
Double check the user your trying to connect to server has necessary privileges
If its not your mysql server then,
Ask the provider whether they are supporting remote connections or not.
1st you have to check if your server is supporting remote MySQL database Connection then
You can try this MySQL Connection String Builder example, i'm working with all the time .. no errors :
_connectionStr = new MySqlConnectionStringBuilder
{
Server = "127.0.0.1",
Database = myDatabase,
UserID = myUserName,
Password = myPassword,
ConnectionTimeout=60,
Port = 3306,
AllowZeroDateTime = true
};
_con = new MySqlConnection(_connectionStr.ConnectionString);
try
{
_con.Open();
}
catch
{
MessageBox.Show("Error, help i can't get connected!");
}
Hope this works!
Maybe your MySQL Server is not configured to listen to any of your IP Interface.
Maybe it is just listening into your "localhost:3306"
Check it in your MySQL Server config file "bind-address".

Error while opening a connection to MS Access 2007 file: Cannot open the MS Office Access database engine workgroup information file

Cannot open the MS Office Access database engine workgroup information file - When I have code as posted.
What I am trying to do in my code is to create MS Access 2007 file and then set the user name and password to it from my program. What am I doing wrong here?
Error occurs here: objOleDbConnection.Open();
EDIT: I have made some changes, seems like it opens a connection but the command is incorrect.
Now problem is here:
objOleDbCommand.CommandText =
"ALTER USER " + storedAuth.UserName +
" PASSWORD [" + storedAuth.Password + "] []";
The entire code:
// Creating an object allowing me connecting to the database.
OleDbConnection objOleDbConnection = new OleDbConnection();
objOleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + sfdNewFile.FileName + ";Persist Security Info=False";
// Creating command object.
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.Connection = objOleDbConnection;
try
{
objOleDbConnection.Open();
objOleDbCommand.CommandText = "ALTER USER " +
storedAuth.UserName + " PASSWORD [" +
storedAuth.Password + "] []";
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
objOleDbConnection.Close();
}
To change an Access DB password, you must it open in exclusive mode. Try adding this to your connection string ;Exclusive=1.
createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Exclusive=1;Data Source=" +
sfdNewFile.FileName);
Well, the error you are getting suggests someone else is keeping the file open, which prevents the password change...
HelpNeeder, I think the problems you are experiencing should first be solved in your other question:
Error tells me I haven't close the connection, but haven't I?
Thanks!

Error Opening Access Database with C# Application

I'm updating a C# (.NET 3.5) application to interact with an Access database, but I keep getting this error:
ERROR: Unrecognized database format
This is the code I'm using to open a connection to the database:
String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + filePath;
try
{
this.conn = new OleDbConnection(connectionString);
this.conn.Open();
}
catch (Exception e)
{
Console.WriteLine("ERROR: " + e.Message);
Console.WriteLine(e.ToString());
}
I know that the file path is correct. I suspect that the Provider=Microsoft.Jet.OLEDB.4.0; is incorrect. How do I find out what the database format is? I did not make the database in question, but I do have read-access to it. Thanks.
You must add Data Source , user/password parametters . You can see http://connectionstrings.com/access

C# connecting to a database

I Am Trying to create a program using c# that needs to connect to a database running on a Solaris server, I am not too familiar with the server, we normally use dbVisualizer to connect to it. the driver it uses to connect is mysql-connector-java-5.1.10, which is a jdbc driver. was wondering what drivers to use to connect to the database using C# and what is the syntax used to establish the connection. as far as I know I will be unable to install any drivers on the server side, and i will only be able to make changes/Install what is required on the client.
If I read your question correctly you are trying to connect to a MySql database from c#. This can be achieved by downloading the .net connector for MySql - Connector/Net. When you install this driver it will "integrate" with Visual Studio and you will be able to connect to the server directly from Visual Studio and your Program that will use the driver.
On the question on the syntax to connect you will either need to use MySqlConnection, with a tutorial here - http://bitdaddys.com/MySQL-ConnectorNet.html, or use something like the ADO.NET Entity Framework. But that depends on your Tastes.
I am assuming this Server can be access over the network.
Update User Confused about Connection String
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
You pass that string to the connection without any JDBC:// prefixes.
Please Note haven't done this in a while so the connection string could be wrong (So correct me If I'm wrong) and if you forget any connection string in the future you can always use a website like http://www.connectionstrings.com/ which shows them all for you. That is where I got the string above.
Hope that helps.
I believe this is what you want to connect (on the server):
http://dev.mysql.com/downloads/connector/net/1.0.html
You can try your connection like this:
string MyConString = "SERVER=yourserver;" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
You would probably want to follow the normal guidelines for IDisposable classes (use using etc.).
using MySql.Data.MySqlClient;
using System.Windows;
class Connexion
{
public MySql.Data.MySqlClient.MySqlConnection connexion;
private string server;
private string database;
private string uid;
private string password;
public Connexion()
{
server = "localhost";
database = "GestionCommeriale";
uid = "root";
password = "";
String connexionString;
connexionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" +
"UID" + uid + ";" + "PASSSWORD =" + password + ";";
connexion = new MySqlConnection(connexionString);
}
public bool OpenConnexion()
{
try
{
connexion.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
public bool ColseConnexion()
{
try
{
connexion.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}

Categories