Wednesday, August 25, 2010

How to use mySQL with .Net

Add mySQL connector
In order to use mySQL with .Net you need to download the connector from the next web site:

http://dev.mysql.com/downloads/connector/net/


Add mySQL connector to your project
On your project right click on "References" ans select "Add Reference..."
Browse to the folder where you installed the connector and open the folder "Assemblies"
Add the MySql dlls

Use connector en your code
Now you can use the connector in your code to access mySQL database




using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace mySQLExample
{
///
/// Summary description for dbConnection.
///

public class dbConnection
{
private string connectionString;

public dbConnection()
{
connectionString = "Server=MySqlServer;Database=MySqlDB;Uid=MySqlUser;Pwd=MySQLPsw;Port=3306;old guids=true";
}


public DataSet ExecuteQuery(CommandType cmdType, string cmdText, params System.Data.Common.DbParameter[] cmdParms)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds, "dataset");
cmd.Parameters.Clear();
return ds;
}
}
}
}

public int ExecuteNonQuery(CommandType cmdType, string cmdText, params System.Data.Common.DbParameter[] cmdParms)
{
MySqlCommand cmd = new MySqlCommand();

using (MySqlConnection conn = new MySqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}

private static void PrepareCommand(System.Data.Common.DbCommand cmd, System.Data.Common.DbConnection conn, System.Data.Common.DbTransaction trans, CommandType cmdType, string cmdText, System.Data.Common.DbParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open) conn.Open();

cmd.Connection = conn;
cmd.CommandText = cmdText.Replace("@", "?").Replace(":", "?");

if (trans != null) cmd.Transaction = trans;

cmd.CommandType = cmdType;

if (cmdParms != null)
{
foreach (MySqlParameter parm in cmdParms)
{
parm.ParameterName = parm.ParameterName.Replace("@", "?").Replace(":", "?");
cmd.Parameters.Add(parm);
}
}
}

}
}








No comments:

Post a Comment