r/PythonLearning • • 1d ago

Showcase Database prototype (python)

I write my first data base code handling a class record using list tell me how is it..

First two are code and the rest is the output.

Tell me if anything can be improve or added to make this code even more practical.

215 Upvotes

27 comments sorted by

2

u/Naive_Programmer_232 1d ago edited 1d ago

nice work. for your remove_data function, look into .pop method on dictionaries. if the name is in the dictionary, you can pop by key (it returns the value), and also updates. so to give example:

    data={
       "Joe": 32,
       "Jack": 58,
    }

    name=input("Enter a name: ").title()
    # user inputs 'jack' .title makes it 'Jack' 
    
    # remove Jack
    _=data.pop(name)
   
    # look at data
    for k,v in data.items():
        print(f"{k}: {v}")
    # output:
    # Joe: 32

you could wrap this in a try, because if something is requested that is not a key, it'll throw a KeyError. So consider this other example:

     def delete_key(d: dict[str,int], key: str) -> None:
         try:
              _=d.pop(key)
         except KeyError:
              print(f"key '{key}' does not exist in dictionary")

    data={
       "Chris": 21,
       "Sarah": 45,
    }
    delete_key(data,"Sarah")
    print(data)
    # {"Chris": 21}
    delete_key(data,"John")
    # key 'John' does not exist in dictionary

that way if it's wrapped you can handle the error without crashing the program and do whatever.

4

u/Traditional-Rub354 19h ago

Holy print statement from hell, why!

2

u/Hidayat8811 19h ago

Which one , I wrote many hell ones 🙂

21

u/PureWasian 1d ago

Persistence. Your database is wiped as soon as you exit the runtime. A natural next progression would be writing the input/output data into a text/csv/json file per "session" running the script.

Then you'll realize, it only saves all of the updates if things exit gracefully. You should update per db write transaction.

Then you'll realize, only one person can edit the db at a time. You should add a locking mechanism so you don't have concurrent writes.

At this point, you'll discover that it's probably a good time to look into sqlite for a more "proper" local, lightweight db layer. Use that to learn how to write queries (and note that you would need to update a lot of your calling code accordingly).

If you wanted to go further, branch out from sqlite to PostgreSQL or some other more beefy and feature-rich db layer, or look into how cloud hosting solutions work to see how people typically save, access, and modify persistent data across multiple users.

1

u/Hidayat8811 1d ago

I agree that it is not storing data any where it is just taking input and printing it . So as many of you said that I should do this in sqlite or in json, where do I start learning them from, what are the differences between them and which best for what. I will improve my code as much as I can .

1

u/potassiumgoth 1d ago

hey,

first of all, i saw you writing about doing some back-end stuff. check this site out:

https://thebackendos.com

i’m currently going through it and it’s free since its beta. i’m not affiliated with them, just enjoy the bite-size content and found it months ago on reddit.

SQL:

i’m part of an open-source project and recently went through designing and building our database. we ultimately ended up using PostgreSQL but it was first designed to be for SQLite. i can post some links that helped us make the decisions we did.

https://www.mindstudio.ai/blog/what-is-sqlite

https://realpython.com/prevent-python-sql-injection/#creating-a-database

https://gist.github.com/jtrive84/38faee556a5106c4be9c38635f3ec2e5

https://www.sqlitetutorial.net/sqlite-python/

https://www.w3schools.com/sql/sql_check.asp

(a ton of w3schools and python documentation used)

https://cheatsheetseries.owasp.org/cheatsheets/Database_Security_Cheat_Sheet.html

https://github.com/enisaeu/enisa-sbd-playbook/blob/main/playbooks/01-trust-boundaries-and-threat-modelling.md

good luck, im learning too!

1

u/PureWasian 1d ago edited 1d ago

I gave an incremental progression in other comment already, but JSON is just a data format very similar to python dictionaries in that you have keys and values and they can be nested.

sqlite you can think of as somewhat like setting up and storing data into CSV tables. You'll want to learn how to set up a basic table schema and implement the CRUD (create/read/update/delete) operations for it, similar to what your Python function calls are doing to modify your current code's data dictionary.

JSON is good for small amounts of data where you're fine loading and overwriting the entire file every time you make a change. sqlite can be better once your data grows, or when you need to quickly search, filter, and safely update specific entries without rewriting the whole file.

4

u/zztopsboatswain 1d ago

This is a good prototype. Now look into SQLite or json to store the data, so you can save your changes

3

u/Sea-Ad7805 1d ago

See this quick demo of the sqlite3 database API. You store your data in tables, not in Python lists, and use SQL statements to query/modify your data.

2

u/No_Connection_2406 1d ago

It’s an interesting experiment but I’d use different tools. If you really want to write a database using python, start with Django.

2

u/Bmoneysign 9h ago

looking good! this is what a lot of computer science courses teach at first ! I’d recommend taking a look at Redis, SQL, And MongoDB for utilizing databases in your coding journey! Don’t let the other comments get you down. What you are working on is a great way to get experience writing code.

2

u/PHASEONE10843 7h ago

Great!
Now, think about how you could make all of this persistent.

2

u/Ender_Locke 1d ago

this is data, in lists not in a database

1

u/_GreyPrinceZot3_ 1d ago

cool, but this is just data as it is. make a function that saves data in a file (use jason, yaml or even ur custom parsing if you wanna do it for fun, its not that hard) everytime soemthing gets chenged, or when you want. if you want, i can send you a lil useless project that i made a few months ago

1

u/Sidjeno 1d ago

use enums and named variable instead of magic variables.

Use an actual storage system, be it sqlite or json.

Tackle all the edge cases and make the system robust.

Develop a test suite to check for those edge cases.

1

u/RyanDubois43 1d ago

add a function to search records by name or ID, and use dicts instead of lists for faster lookups.

1

u/_DetectiveBrainz342 23h ago

Bro that is amazing

1

u/ArtynLuck 16h ago

That print statement cascade is terrifying. For starters stick your data in a JSON file before you accidentally summon a memory leak.

1

u/Darthbyte_final_boss 9h ago

Yeah that's amazing 👏

1

u/hishahidullah 9h ago

After a lot of days later i saw the print()
Before claude code i use this everyday fore very problem fixing lol now it's like rare things

1

u/Old-Confection-5129 3h ago

Each entity can be its own json file in a folder, and you can do all your normal crud stuff that way. That would be a good next step since you are working on the interface. Keep going!

1

u/sleepbot63 1d ago

What's the goal may I ask ? coz I don't see a database here actually

0

u/[deleted] 1d ago

[deleted] — view deleted comment

1

u/sleepbot63 1d ago

Brother I just saw "Database" and asked what the goal of the project was ? So I could assist better...where tf is the "rude" part ???