How to connect to MySQL by using ADO .NET and C# 4.0

Download the MySQL drivers at: http://dev.mysql.com/downloads/connector/net/

Install the drivers on you’re development machine.

 

At references to:

– System.Data

– MySql.Data [C:\Program Files (x86)\MySQL\MySQL Connector Net 6.4.3\Assemblies\v4.0\MySql.Data.dll]

 

The following code will output all database names to the console window:

using System.Data;
using MySql.Data.MySqlClient;
string connectionString = String.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
"192.168.1.1", "3306", "MyDatabaseName1", "MyUserName1", "MyPassword1"); using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand("SHOW DATABASES", connection)) { connection.Open(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.GetString(0)); } } }

How to query a Microsoft SQL Server database with Microsoft ADO .NET 3.5

The following C# code will query a log table on a Microsoft SQL Server database by using Microsoft ADO .NET 3.5:
        public bool DoesLogTableContainMessage(stringmessage)
        {
            bool result = false;
            using(DataTable dataTable = newDataTable())
            {
                using(SqlConnection connection = newSqlConnection(ConfigurationManager.ConnectionStrings["UnittestDb"].ConnectionString))
                {
                    connection.Open();
                    using(SqlDataAdapter adapter = newSqlDataAdapter("select * from adalog where [message] like ‘test%’", connection))
                    {
                        int rowsAffected = adapter.Fill(dataTable);
                    }
                }
                if(dataTable.Rows.Count > 0)
                    result = true;
            }

            returnresult;
        }

The following C# code will execute a truncate table on a log table on a Microsoft SQL Server database by using Microsoft ADO .NET 3.5:
            using (SqlConnection connection = newSqlConnection(ConfigurationManager.ConnectionStrings["UnittestDb"].ConnectionString))
            {
                connection.Open();
                using(SqlCommand command = newSqlCommand("truncate table adalog", connection))
                {
                    int rowsAffected = command.ExecuteNonQuery();
                }
            }