From 65f1e74db8f99ce89fc2ca956b29b81de81a5963 Mon Sep 17 00:00:00 2001 From: Felix Date: Mon, 9 May 2022 14:20:09 +0200 Subject: [PATCH] database connection working --- Database.cs | 61 +++++++++++++++++++++++++++++++++++------------------ Form1.cs | 4 ++-- 2 files changed, 43 insertions(+), 22 deletions(-) diff --git a/Database.cs b/Database.cs index ea63cae..1b00e37 100644 --- a/Database.cs +++ b/Database.cs @@ -1,20 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Data.Common; -using System.Data.Entity; - -namespace it_projekt -{ - class Database : DbContext - { - public virtual DbSet persons { get; set; } - public Database(String connectionString) - : base(connectionString) - { - - } - } -} +using System; +using System.Collections.Generic; +using MySql.Data; +using MySql.Data.MySqlClient; + +namespace it_projekt +{ + class Database + { + public List Persons { get; set; } + public Database(String username, String password) + { + string connectionString = "server=localhost;port=3306;database=stammdaten;User Id=" + username + ";Password=" + password + ";"; + MySqlConnection connection = new MySqlConnection(connectionString); + try + { + Console.WriteLine("Connecting to MySQL..."); + connection.Open(); + + string sql = "SELECT * FROM stammdaten"; + MySqlCommand cmd = new MySqlCommand(sql, connection); + MySqlDataReader rdr = cmd.ExecuteReader(); + Persons = new List(); + while (rdr.Read()) + { + Person p = new Person(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString(), DateTime.Parse(rdr[3].ToString())); + Persons.Add(p); + + } + rdr.Close(); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + + connection.Close(); + Console.WriteLine("Done."); + } + } +} diff --git a/Form1.cs b/Form1.cs index d170eaa..b956114 100644 --- a/Form1.cs +++ b/Form1.cs @@ -36,8 +36,8 @@ namespace it_projekt public static void LoadUsersFromTable(string user, string password) { - Database test = new Database(user, password); - MessageBox.Show(test.Person.Firstname); + Database db = new Database(user, password); + MessageBox.Show(db.Persons.ToString()); } private void dataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)