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 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C# 查询 MariaDB 数据库
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01