Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a MariaDB database with C#

Tags:

c#

.net

sql

mariadb

I have XAMPP installed on Windows, and MySQL setup.

I was wondering how I could query my database from C#.

I can already connect using MySql.Data.MySqlClient.MySqlConnection.

I am looking for a string in the database, and if it is there, popup a messagebox saying Found!. How would I do this?

like image 503
Jacob Collins Avatar asked Jun 23 '17 10:06

Jacob Collins


1 Answers

Here is a sample code to make application connect to your Database

string m_strMySQLConnectionString;
m_strMySQLConnectionString = "server=localhost;userid=root;database=dbname";

Function to get String value from DB

private string GetValueFromDBUsing(string strQuery)
    {
        string strData = "";

        try
        {                
            if (string.IsNullOrEmpty(strQuery) == true)
                return string.Empty;

            using (var mysqlconnection = new MySqlConnection(m_strMySQLConnectionString))
            {
                mysqlconnection.Open();
                using (MySqlCommand cmd = mysqlconnection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandTimeout = 300;
                    cmd.CommandText = strQuery;

                    object objValue = cmd.ExecuteScalar();
                    if (objValue == null)
                    {
                        cmd.Dispose();
                        return string.Empty;
                    }
                    else
                    {
                        strData = (string)cmd.ExecuteScalar();
                        cmd.Dispose();
                    }

                    mysqlconnection.Close();

                    if (strData == null)
                        return string.Empty;
                    else
                        return strData;                        
                }                    
            }                                
        }
        catch (MySqlException ex)
        {
            LogException(ex);
            return string.Empty;
        }
        catch (Exception ex)
        {
            LogException(ex);
            return string.Empty;
        }
        finally
        {

        }
    }

Your Function code in Button Click Event

  try
  {
     string strQueryGetValue = "select columnname from tablename where id = '1'";
     string strValue = GetValueFromDBUsing(strQueryGetValue );
     if(strValue.length > 0)
     {
           MessageBox.Show("Found");
          MessageBox.Show(strValue);
     }

     else
         MessageBox.Show("Not Found");         
  }
  catch(Exception ex)
  {
      MessageBox.Show(ex.Message.ToString()); 
  }
like image 97
SH7 Avatar answered Sep 20 '22 16:09

SH7