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?
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With