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 数据库
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
