Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Eine eigene Datenbank (Modularisierung und Delegation)

Entwerfen Sie ein Programm womit Eingaben von Benutzern gespeichert werden:

 

Dies wären z. B. Name, Alter, Geburtsdatum, Wohnort, ...

 

Außerdem sollten diese jederzeit wieder abrufbar sein.

 

Viel Glück

 

 

PS: Strukturen (auch bekannt als Records, Structs, Klassen, Datenkapseln) würden nicht schaden

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

5 Lösung(en)

import sqlite3

#Erstellen der Datenbank
createDB = sqlite3.connect("mydatabase.db")
cursor = createDB.cursor()

#Erstellend der Tabelle
def createTable():
    cursor.execute("CREATE TABLE IF NOT EXISTS kunden (ID INTEGER PRIMARY KEY AUTOINCREMENT, namen TEXT, vorname TEXT, alterJahre REAL)")

#Einfügen der Daten in die Tabelle
def insertIntoDatabase():
    cursor.execute("INSERT INTO kunden (namen, vorname, alterJahre) VALUES ('TOM' , 'Huber', 22.3)")
    

#Lesen der Daten aus der Tabelle
def readFromDatabase():
    cursor.execute ("SELECT * FROM kunden")
    read = cursor.fetchall()
    print(read)
    
                               
#createTable()    #erstellen der Tabelle                   
insertIntoDatabase()
readFromDatabase()

createDB.commit()

                

Lösung von: Py Thon ()

require "date"

# Global thingies:
$database       = nil
help_string = "Available commands:\n\nlist\nsave\nload\nadd\nremove\nexit"

class Person
    # Init:
    
    def initialize(name = "Foobar", age = 99, dob = Date.new(1900, 1, 1), address = "Barfoo-St. 99")
        @name      = name
        @age       = age
        @dob       = dob
        @address   = address
    end
    
    
    # Getter, Setter:
    
    def set_name(new_name)
        if (new_name.is_a(String))
            @name = new_name
        else
            raise TypeError.new("New name is not a String.")
        end
    end
    
    def get_name()
        return @name
    end
    
    def set_age(new_age)
        if (new_age.is_a(Integer))
            @age= new_age
        else
            raise TypeError.new("New age is not an Integer.")
        end
    end
    
    def get_age()
        return @age
    end
    
    def set_dob(new_dob)
        if (new_name.is_a(Date))
            @dob = new_dob
        else
            raise TypeError.new("New date of birth is not a Date.")
        end
    end
    
    def get_dob()
        return @dob
    end
    
    def set_address(new_address)
        if (new_address.is_a(String))
            @address = new_address
        else
            raise TypeError.new("New address is not a String.")
        end
    end
    
    def get_address()
        return @address
    end
    
end


def comment(str)
    puts "\e[32m#{">>> " + str}\e[0m"
end

def load_database()

    comment("Trying to load database.")

    database_file = File.open("db.txt", "a+")
    $database = Array.new
    
    database_file.each do |line|
        fields = line.split(",")
        
        begin
            $database << Person.new(fields[0], fields[1].to_i(), Date.new(fields[2].to_i(), fields[3].to_i(), fields[4].to_i()), fields[5].to_i())
        rescue TypeError
            comment("The database seems corrupted - exiting.")
            abort("Loading database failed...")
        end
    end
    database_file.close()
    comment("Loading finished.")
end

def save_database()
    database_file = File.open("db.txt", "w+")
    
    $database.each do |person|
        database_file.write("#{person.get_name()},#{person.get_age()},#{person.get_dob().to_s().gsub("-", ",")},#{ + person.get_address()}\n")
    end

    database_file.close()

end

def input(str = "")
    comment(str)
    print "> "
    return gets.chomp
end

def add_person()
    comment("Adding a person.")
    
    name = input("Name?")
    
    age = input("Age?").to_i()
    
    dob = Date.parse(input("Date of birth? (yyyy-mm-dd)"))
    
    address = input("Address?")
    
    $database << Person.new(name, age, dob, address)
end

def remove_person()
    comment("Removing a person.")
    nr = input("Enter the number in list (leave blank for abort):").to_i()
    $database.delete($database[nr - 1]) {comment( "Couldn't find the person.")}
end

def print_database()
    comment("Listing the database:")
    n = 1 # add 1 to index to allow aborting remove via filtering 0
    $database.each do |p|
       name = p.get_name()
       age = p.get_age().to_s()
       dob = p.get_dob().to_s()
       address = p.get_address()
       
       str = "[#{n}]\nName: #{name} \nAge: #{age}\nDate of birth: #{dob}\nAddress: #{address}\n"
       comment(str)
       n+=1
    end
    comment("Done.")
end

load_database()
comment("Try entering 'help'.")

while true
    input = input("How can I help you?")
    case input
        when "load"
            load_database()
        when "save"
            save_database()
        when "help"
            comment(help_string)
        when "add"
            add_person()
        when "remove"
            remove_person()
        when "list"
            print_database()
        when "exit"
            exit()
    end
end






                

Lösung von: Ich Bins (tubs)

// NET 6.x | C# 10.x | VS-2022

// Datenbank (vereinfacht)
var idCounter = 4;
var dbPersons = new List<Person>() {
    new(1, "Meier", "Ingrid", new DateOnly(1955, 11, 22), "28224"),
    new(2, "Müller", "Jochen", new DateOnly(1967, 6, 5), "28111"),
    new(3, "Müller", "Frank", new DateOnly(1952, 3, 28), "55744"),
    new(4, "Schulze", "Jürgen", new DateOnly(1955, 7, 5), "16111")
};

// Methoden
void AddPerson() {
    Console.Write("Nachname: ");
    var lastname = Console.ReadLine();
    Console.Write("Vorname: ");
    var firstname = Console.ReadLine();
    Console.Write("Geburtsdatum (TT.MM.JJJJ): ");
    _ = DateOnly.TryParse(Console.ReadLine(), out var birthday);
    Console.Write("PLZ: ");
    var zipcode = Console.ReadLine();
    if (string.IsNullOrEmpty(zipcode) || string.IsNullOrEmpty(lastname) || string.IsNullOrEmpty(firstname)) return;
    dbPersons.Add(new(++idCounter, lastname, firstname, birthday, zipcode));
}
static void PrintDb(List<Person> lstPerson) => lstPerson.ForEach(p => Console.WriteLine(p));

// Ein- und Ausgabe
AddPerson();
PrintDb(dbPersons);

// Struct 'Person'
public record struct Person(int Id, string Lastname, string Firstname, DateOnly Birthday, string Zipcode) {
    public int Age => DateTime.Now.Year - Birthday.Year + (new DateTime(DateTime.Now.Year, Birthday.Month, Birthday.Day) > DateTime.Now ? -1 : 0);
}
                

Lösung von: Jens Kelm (@JKooP)

// C++ 14 | VS-2022

#include <iostream>
#include <vector>

auto id_counter{ 4 };

struct Person {
    const int id{++id_counter};
    std::string lastName;
    std::string firstName;
    size_t age{0};
    std::string zipcode;
};

std::vector<Person> db_persons {
    { 1, "Meier", "Ingrid", 67, "28224" },
    { 2, "Müller", "Jochen", 55, "28111" },
    { 3, "Müller", "Frank", 70, "55744" },
    { 4, "Schulze", "Jürgen", 67, "16111" }
};

void add_person() {
    Person person;
    std::cout << "Nachname: ";
    std::cin >> person.lastName;
    std::cout << "Vorname: ";
    std::cin >> person.firstName;
    std::cout << "Alter: ";
    std::cin >> person.age;
    std::cout << "PLZ: ";
    std::cin >> person.zipcode;
    db_persons.push_back(person);
}

void print_db() {
    std::locale::global(std::locale("German_germany.UTF-8"));
    for (const auto& p : db_persons)
        std::cout << p.id << ", " << p.lastName << ", " << p.firstName << ", " << p.age << ", " << p.zipcode << std::endl;
}

int main() {
    add_person();
    print_db();
}
                

Lösung von: Jens Kelm (@JKooP)

function giveId() {
  localStorage.curId ? localStorage.curId++ : localStorage.curId = 1;
  return parseInt(localStorage.curId);
}

class User {
  constructor(input) {
    this.firstName   = input.firstName || undefined;
    this.lastName    = input.lastName || undefined;
    this.residence   = input.residence || undefined;
    this.dateOfBirth = input.dateOfBirth || undefined;
    this.points      = input.points || 0;
    this.premium     = input.premium || false;
    this.id          = input.id || giveId();
  }
  get fullName() { return `${this.firstName} ${this.lastName}`; }
  get age() {
    let dob = new Date(this.dateOfBirth),
        now = new Date(),
        y   = now.getFullYear() - dob.getFullYear();
    if (now.getMonth() > dob.getMonth()) return y;
    if (now.getMonth() < dob.getMonth()) return y-1;
    if (now.getMonth() == dob.getMonth()) {
      if (now.getDay() > dob.getDay()) return y;
      if (now.getDay() < dob.getDay()) return y-1;
      if (now.getDay() == dob.getDay())
      return `Glückwunsch zum Geburtstag, ${this.firstName}!`;
    }
  }
}

let users;
const USER_DB = {
  add: function(data) {
    if (!data) {
      let newser = new User({});
      newser.firstName = prompt('Vorname:');
      newser.lastName = prompt('Nachname:');
      newser.residence = prompt('Wohnort:');
      let dob = prompt('Geburtsdatum (dd.mm.yyyy):').split('.');
      for (let x in dob) parseInt(x);
      newser.dateOfBirth = new Date(dob[2], dob[1]-1, dob[0]);
      newser.points = parseInt(prompt('Punkte:'));
      newser.premium = confirm('Premium?');
      users.push(newser);
    } else users.push(new User(data));
  },
  clear: function() {
    users = [];
    localStorage.curId = 0;
  },
  deleteById: function(id) {
    let i = 0;
    while (users[i].id != id) i++;
    users.splice(i, 1);
  },
  load: function() {
    if (localStorage.users) {
      users = JSON.parse(localStorage.users);
      for (let x = 0; x < users.length; x++) users[x] = new User(users[x]);
    } else {
      console.info('Datenbank wurde angelegt.');
      users = [];
    }
  },
  print: function() {
    let out = `<h1>Userliste</h1>`;
    for (let i = 0; i < users.length; i++) {
      out += (`
        <h2>#${users[i].id}: ${users[i].fullName} (${users[i].points})
      `);
      if (users[i].premium) out += ('*</h2>');
      else out += ('</h2>');
      out += (`
        <p>Alter ${users[i].age}, ${users[i].residence}</p>
      `);
    }
    return out;
  },
  save: function() { localStorage.users = JSON.stringify(users); },
  sortByPoints: function() {
    users.sort(function(a, b) {
      if (a.points > b.points) return -1;
      if (a.points < b.points) return 1;
      return 0;
    })
  }
}

/*---------------*\
|  E I N S A T Z  |
\*---------------*/

function output() { monitor.innerHTML = USER_DB.print(); }
// button handler
function hLoad() { USER_DB.load(); output(); }
function hAdd()  { USER_DB.add(); output(); }
function hSort() { USER_DB.sortByPoints(); output(); }
function hClr()  { USER_DB.clear(); output(); }
function hDel()  {
  USER_DB.deleteById(parseInt(prompt('ID:')));
  output();
}

window.addEventListener('load', USER_DB.load());
window.addEventListener('unload', function() {
  if (confirm('Datenbank speichern?')) USER_DB.save();
});

// eingabemaske
document.write(`
  <button onclick="hAdd()">Hinzufügen...</button>
  <button onclick="hLoad()">Neu laden</button>
  <button onclick="USER_DB.save()">Speichern</button>
  <button onclick="hSort()">Sortieren</button>
  <button onclick="hDel()">ID löschen...</button>
  <button onclick="hClr()">Leeren</button>
  <div id="monitor"></div>
`);
let monitor = document.getElementById('monitor');

// serviervorschlag
USER_DB.add({
  firstName: 'Helga', lastName: 'Feddersen',
  residence: 'Hamburg', dateOfBirth: new Date(1930, 2, 14),
  points: 499, premium: true
});
USER_DB.add({
  firstName: 'Ivan', lastName: 'Rebroff',
  residence: 'Berlin', dateOfBirth: new Date(1931, 6, 31),
  points: 501, premium: false
});
output();

                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 1
Schwierigkeit: Mittel
Webcode: uahd-skr3
Autor: ()

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen