I det følgende vil vi skabe en forbindelse mellem C# og MariaDB.
For forbinde fra C# VS til MariaDB kræves en 'Connector' (driver). Denne driver kan installeres i VS under tools. (Se nedenstående billede)
Søg efter MySQLConnector og installer denne. (se nedenstående billede)
Denne video demonstrerer hvordan man forbinder til en MariaDB/MySQL database fra konsollen. Der laves yderligere en metode til at håndtere en 'insert' i en tabel.
OBS !! I skal istedet for 'using MySQL.Data' bruge:
using MySqlConnector;
Følg eksemplet og implementer selv en klasse der kan forbinde til din egen database, samt metoder for 'INSERT' og 'DELETE' i databasen.
using System; using System.Data; using MySqlConnector; namespace WinToMariaDB { internal class DBConn { private string server = "localhost"; private string database = "camping"; private string username = "root"; private string password = "xxxxxxxx"; MySqlConnection connection; public DBConn() { Connect(); } private void Connect() { string connectionString = $"Server={server};Database={database};User={username};Password={password};"; connection = new MySqlConnection(connectionString); try { connection.Open(); } catch (Exception ex) { Console.WriteLine($"Error opening database: {ex.Message}"); } finally { connection.Close(); } } public bool CloseConnection(){ if (this.connection.State == ConnectionState.Open) { connection.Close(); return true; } return false; } public bool OpenConnection(){ if (this.connection.State == ConnectionState.Closed) { connection.Open(); return true; } return false; } public MySqlConnection GetConnection() { return this.connection; } } }