Programm_Wirl/Maschine.cs
2025-11-30 11:44:05 +01:00

87 lines
2.9 KiB
C#

using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatenDB
{
public class Maschine
{
public const string COLUMNS = "maschine_id, faecher, bezeichnung, trockner_kaputt";
private const string TABLE = "kundenverwaltung.maschine";
public static Maschine GetMaschine(int? mID, string bezeichnung)
{
DatenbankConnection.GetConnection().Open();
Maschine result = null;
NpgsqlCommand command = new NpgsqlCommand();
command.Connection = DatenbankConnection.GetConnection();
if (string.IsNullOrEmpty(bezeichnung)) command.CommandText = $"select {COLUMNS} from {TABLE} where maschine_id = {mID}";
if (mID == null) command.CommandText = $"select {COLUMNS} from {TABLE} where bezeichnung = '{bezeichnung}'";
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read()) result = new Maschine(reader);
reader.Close();
DatenbankConnection.GetConnection().Close();
return result;
}
public static List<Maschine> GetList()
{
DatenbankConnection.GetConnection().Open();
List<Maschine> resultList = new List<Maschine>();
NpgsqlCommand command = new NpgsqlCommand();
command.Connection = DatenbankConnection.GetConnection();
command.CommandText = $"select {COLUMNS} from {TABLE}";
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read()) resultList.Add(new Maschine(reader));
reader.Close();
DatenbankConnection.GetConnection().Close();
return resultList;
}
public Maschine()
{
} // LEER
public int? MaschineID { get; set; }
public int Faecher { get; set; }
public string Bezeichnung { get; set; }
public bool TrocknerKaputt { get; set; }
public Maschine(NpgsqlDataReader reader)
{
this.MaschineID = reader.GetInt32(0);
this.Faecher = reader.GetInt32(1);
this.Bezeichnung = reader.GetString(2);
this.TrocknerKaputt = reader.IsDBNull(3) ? false : reader.GetBoolean(3);
}
public int Save()
{
DatenbankConnection.GetConnection().Open();
NpgsqlCommand command = new NpgsqlCommand();
command.Connection = DatenbankConnection.GetConnection();
if(this.MaschineID.HasValue & this.MaschineID != 0)
{
command.CommandText = $"update {TABLE} set faecher = :p1, bezeichnung = :p2, trockner_kaputt = :p3 where maschine_id = :p0";
}
else
{
command.CommandText = "select nextval('kundenverwaltung.maschine_seq')";
this.MaschineID = (int)(long)command.ExecuteScalar();
command.CommandText = $"insert into {TABLE} ({COLUMNS}) values (:p0, :p1, :p2, :p3)";
}
command.Parameters.AddWithValue("p0", this.MaschineID);
command.Parameters.AddWithValue("p1", this.Faecher);
command.Parameters.AddWithValue("p2", this.Bezeichnung);
command.Parameters.AddWithValue("p3", this.TrocknerKaputt);
int result = command.ExecuteNonQuery();
DatenbankConnection.GetConnection().Close();
return result;
}
}
}