database connection working

This commit is contained in:
2022-05-09 14:20:09 +02:00
parent c2ec941eae
commit 65f1e74db8
2 changed files with 43 additions and 22 deletions

View File

@@ -1,20 +1,41 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using MySql.Data;
using System.Text; using MySql.Data.MySqlClient;
using System.Threading.Tasks;
using System.Data.Common; namespace it_projekt
using System.Data.Entity; {
class Database
namespace it_projekt {
{ public List<Person> Persons { get; set; }
class Database : DbContext public Database(String username, String password)
{ {
public virtual DbSet<Person> persons { get; set; } string connectionString = "server=localhost;port=3306;database=stammdaten;User Id=" + username + ";Password=" + password + ";";
public Database(String connectionString) MySqlConnection connection = new MySqlConnection(connectionString);
: base(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<Person>();
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.");
}
}
}

View File

@@ -36,8 +36,8 @@ namespace it_projekt
public static void LoadUsersFromTable(string user, string password) public static void LoadUsersFromTable(string user, string password)
{ {
Database test = new Database(user, password); Database db = new Database(user, password);
MessageBox.Show(test.Person.Firstname); MessageBox.Show(db.Persons.ToString());
} }
private void dataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e) private void dataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)