使用 C# 查询 MariaDB 数据库

Jac*_*ins 5 .net c# sql mariadb

我在 Windows 上安装了 XAMPP,并安装了 MySQL。

我想知道如何从 C# 查询我的数据库。

我已经可以使用MySql.Data.MySqlClient.MySqlConnection.

我在数据库中寻找一个字符串,如果它在那里,弹出一个messagebox说法Found!。我该怎么做?

小智 5

这是使应用程序连接到数据库的示例代码

string m_strMySQLConnectionString;
m_strMySQLConnectionString = "server=localhost;userid=root;database=dbname";
Run Code Online (Sandbox Code Playgroud)

从数据库获取字符串值的函数

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
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

您在按钮单击事件中的函数代码

  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()); 
  }
Run Code Online (Sandbox Code Playgroud)