使用C#查询MariaDB数据库 [英] Querying a MariaDB database with C#
本文介绍了使用C#查询MariaDB数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Windows上安装了XAMPP,并安装了MySQL.
I have XAMPP installed on Windows, and MySQL setup.
我想知道如何从C#查询数据库.
I was wondering how I could query my database from C#.
我已经可以使用MySql.Data.MySqlClient.MySqlConnection
进行连接.
I can already connect using MySql.Data.MySqlClient.MySqlConnection
.
我正在数据库中寻找一个字符串,如果存在,则弹出一个messagebox
并说Found!
.我该怎么办?
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());
}
这篇关于使用C#查询MariaDB数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文