我已经在Windows上安装了XAMPP,并安装了MySQL。
我想知道如何从C#查询我的数据库。
我已经可以使用MySql.Data.MySqlClient.MySqlConnection连接了。
我正在数据库中寻找一个字符串,如果它在那里,就会弹出一个写着Found!的messagebox。我该怎么做呢?
发布于 2017-06-23 19:08:47
以下是使应用程序连接到数据库的示例代码
string m_strMySQLConnectionString;
m_strMySQLConnectionString = "server=localhost;userid=root;database=dbname";从数据库获取字符串值的函数
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
{
}
}Button 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());
}https://stackoverflow.com/questions/44719432
复制相似问题