Click here to Skip to main content
15,891,136 members
Articles / Database Development / MySQL

Connecting to MySQL from Visual C#

Rate me:
Please Sign up or sign in to vote.
4.91/5 (28 votes)
20 Mar 2014CPOL4 min read 163.9K   2.1K   110  
Using Visual C# 2008 to establish connection to a MySQL 5.1 database with MySQL Connector/NET 5.1.7
using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;

namespace MySQLDBConnection
{
    class Program
    {
        private static ConsoleColor defaultColor = Console.ForegroundColor;
        private static ConsoleColor borderColor = ConsoleColor.DarkCyan;

        static void Main(string[] args)
        {
            MySqlConnectionStringBuilder connBuilder =
                new MySqlConnectionStringBuilder();

            connBuilder.Add("Database", "shop");
            connBuilder.Add("Data Source", "localhost");
            connBuilder.Add("User Id", "root");
            connBuilder.Add("Password", "masterkey");

            MySqlConnection connection =
                new MySqlConnection(connBuilder.ConnectionString);

            MySqlCommand cmd = connection.CreateCommand();

            connection.Open();

            InsertCommand(cmd, "MQ95 Flat Monitor", 399.00);
            QueryCommand(cmd);

            connection.Close();
        }

        public static void QueryCommand(MySqlCommand cmd)
        {
            cmd.CommandText = "SELECT * FROM article";
            cmd.CommandType = CommandType.Text;

            MySqlDataReader reader = cmd.ExecuteReader();

            Console.WriteLine("Querying data in table:");
            DrawLine();
            TableHeaders();
            DrawLine();

            while (reader.Read())
            {
                Console.ForegroundColor = borderColor;
                Console.Write("|");
                Console.ForegroundColor = defaultColor;
                Console.Write(String.Format("{0,11} ", reader.GetInt32(0)));

                Console.ForegroundColor = borderColor;
                Console.Write("| ");
                Console.ForegroundColor = defaultColor;
                Console.Write(String.Format("{0,-39}", reader.GetString(1)));

                Console.ForegroundColor = borderColor;
                Console.Write("| ");
                Console.ForegroundColor = defaultColor;
                Console.Write(String.Format("{0,13:F} ", reader.GetDouble(2)));

                Console.ForegroundColor = borderColor;
                Console.Write("| ");
                Console.ForegroundColor = defaultColor;

                Console.WriteLine();
            }
            DrawLine();

            reader.Close();
        }

        public static void InsertCommand(MySqlCommand cmd, string name, double price)
        {
            cmd.CommandText = "append_data";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new MySqlParameter("param_name", name));
            cmd.Parameters.Add(new MySqlParameter("param_price", price));

            cmd.ExecuteNonQuery();
        }

        private static void TableHeaders()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("| article_id ");
            sb.Append(String.Format("{0,-41}", "| article_name "));
            sb.Append("| article_price ");
            sb.Append("|");

            Console.ForegroundColor = borderColor;

            Console.WriteLine(sb.ToString());

            Console.ForegroundColor = defaultColor;
        }

        private static void DrawLine()
        {
            Console.ForegroundColor = borderColor;

            Console.Write("+");
            for (int i = 1; i <= 12; i++)
                Console.Write("-");

            Console.Write("+");
            for (int j = 1; j <= 40; j++)
                Console.Write("-");

            Console.Write("+");
            for (int k = 1; k <= 15; k++)
                Console.Write("-");

            Console.WriteLine("+");
            Console.ForegroundColor = defaultColor;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Guatemala Guatemala
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions