2017-06-23 14 views
0

我在Windows上安装了XAMPP,并安装了MySQL。用C#查询MariaDB数据库

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

我已经可以使用MySql.Data.MySqlClient.MySqlConnection连接了。

我正在查找数据库中的一个字符串,如果它在那里,请弹出一个messagebox,表示Found!。我将如何做到这一点?

+0

获取字符串值你试过了什么? – tym32167

回答

0

这里是一个示例代码,以使应用程序连接到数据库

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

功能从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 
     { 

     } 
    } 

在按钮的Click事件你的函数代码

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()); 
    }