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;
using System.Data.Entity;
namespace it_projekt namespace it_projekt
{ {
class Database : DbContext class Database
{ {
public virtual DbSet<Person> persons { get; set; } public List<Person> Persons { get; set; }
public Database(String connectionString) public Database(String username, String password)
: base(connectionString)
{ {
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<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)