连接MariaDB数据库的操作和连接Mysql的是一样的。
第一步:连接之前需要安装MariaDB数据库10.9之前的版本,不然在conn.Open();时报错:System.InvalidCastException:“Object cannot be cast from DBNull to other types.”
详见:c# - MySqlConnection.Open() System.InvalidCastException: 对象无法从 DBNull 转换为其他类型 - 堆栈内存溢出
第二步:在VisualStudio的NuGet包管理器里安装Mysql.Data
第三步:连接数据库
using MySql.Data.MySqlClient;
//创建连接对象
string connStr = "charset=utf8;server=localhost;database=数据库;user=用户名;password=密码";
MySqlConnection connection = new MySqlConnection(connStr);
//连接数据库
try
{
connection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
//执行SQL语句
string str = "select * from table";
MySqlCommand command = new MySqlCommand(str, connection);
//读取数据库
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read()){
Console.WriteLine(reader[0].ToString());//读取第一列数据
}