MySQL ODBC Connection from C#

 

Requirements
Microsoft Visual studio
MySQL database
MySQL ODBC 5.1 Driver


The Form

Create a form with:

textBox1 (sql command)
textBox2 (sql error message)
listBox1  (query return)
button1   (execute sql button)

 

The Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.Sql;
using System.Data.Odbc;
using System.Data.SqlClient;

namespace odbctest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            try
            {
                string myConnectionString = "Driver={MySQL ODBC 5.1 Driver};Server=*;Database=*; User=*;Password=*;Option=3;";
                OdbcConnection myConnection = new OdbcConnection();
 
                myConnection.ConnectionString = myConnectionString;
                myConnection.Open();

                string mySqlCommand = textBox1.Text;

                OdbcCommand comm = new OdbcCommand(mySqlCommand, myConnection);
                OdbcDataReader dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    int i = 0;
                    string row = "";
                  
                    while(i < dr.FieldCount)
                    {
                        row = row + dr.GetValue(i).ToString();
                        i++;
                    }

                    listBox1.Items.Add(row);                  
                }

                myConnection.Close();
            }
            catch (Exception ex)
            {
                textBox2.Text = ex.Message.ToString();
            }
        }
    }
}
 

 

www.programmingsystems.eu