Simple Python Database Tutorial & Example

In summary, the two ways to create a simple, small database in Python are by using a dictionary or a class.
  • #1
CWatters
Science Advisor
Homework Helper
Gold Member
10,544
2,323
Can anyone refer me to a tutorial or example Python database progam? I'm trying to understand how one might create and manipulate a simple/small database such as a file containing names, addresses, and phone numbers.

I've spent an hour or two searching and keep finding references to SQL and or third party library's designed to make the job easier but I don't think my kids are allowed/expected to use such advanced tools yet.

Darn it my battery is going flat...
 
  • Like
Likes WWGD and atyy
Technology news on Phys.org
  • #2
There is open source C code available in BSD and Solaris called bdb or just db. Because python is a high level implementation with many complex algorithms rolled into library calls, I do not see much of a learning opportunity. I am not knocking python. Nor am I a Luddite. Just that things like hash table based associative arrays - for example - need to be understood at a low level, not just a simple call. I have seen too many Java programmers who are not programmers and fail to understand why some otherwise trivial code eats a $300K machine.

Try this: https://github.com/vinta/awesome-python

Download pickleDB which is a db written in python.
 
  • Like
Likes WWGD and atyy
  • #3
Thanks for the reply. I'm going to check but I think my kids are meant to use just native Python (no add-ons at all) for their exam course work.

I did some more research late last night and it looks like a simple database can be done using a Dictionary (eg for a simple/unsecure Username & password database) or perhaps a "List of Lists" for something slightly more complicated.
 
  • #4
Depending on the number of entries your database is likely to have Just a simple linked list with add, delete and search functions would be OK. Another approach could be a large array and a simple hashing function.

Cheers
 
  • #5
For a database that doesn't have to be scaleable, and that needs only a couple of features, we can use native python:
Python:
python
>>> db = [ { 'Name': 'CWatters', 'Phone': 123456 } ]
>>> print db
[{'Phone': 123456, 'Name': 'CWatters'}]

>>> import json
>>> with open('data.txt', 'w') as outfile:
    json.dump(db, outfile)
After this, 'data.txt' contains:
Code:
[{"Phone": 123456, "Name": "CWatters"}]
It's a good exercise to learn python, learn some basics about data structures, and learn some basics about file I/O.
Good keywords to look for are 'lists', 'dictionaries', and 'json' in python.
 
Last edited:
  • Like
Likes stoomart
  • #6
Well in general there are two simple ways I can think of, one is indeed the dictionary, and the other is a class (well for python classes and dictionaries are not that different). In general list of lists will make the program somewhat complicated in terms of reading and keep track of what's going on (especially if you don't need some kind of ordered inputs).
The class way would be something along these lines:
Python:
class Person():
    def __init__(self, name, phone, pw):
        self.name = name
        self.phone = phone
        self.password = pw
        self.__personList = PersonList()
    #setters
    def set_name ( self, name):
        self.name = name
    def set_phone( self,phone):
        self.phone = phone
    def set_password( self, passw):
        self.password = passw
    #getters
    def get_name( self ):
        return self.name
    def get_phone(self):
        return self.phone
    def get_password(self ):
        return self.password
    #operator overload
    def __eq__(self,other):
        return (self.name==other.name) and (self.password==other.password) and (self.phone==other.phone)
     
class PersonList():
    def __init__(self):
        self.persons = []
    def add(self, person):
        #saves from double counting same person
        if not self.isPersonInList(person):
            self.persons.append(person)
         
    def remove(self, person):
        self.persons.pop(person)
     
    def isPersonInList(self,person):
        for pi in self.persons:
            if person==pi:
                return True
        return False
     
    def Print(self):
        for person in self.persons:
            print "%s : %s (pass) %s (phone)"%(person.name, person.password, person.phone )
     
         
class ReadData():
    def __init__(self, inputFile = None):
        self.personList = PersonList()
        self.inputfile = inputFile
 
    def Run(self):
        if not self.inputfile:
            print "Provide input file to find data"
        else:
            print "Opening to read file : "+self.inputfile
            with open(inputFile,"r") as fin:
                for line in fin:
                    name,phone,passw = line.split(",")
                    name= name.replace(" ","")
                    phone= int(phone.replace(" ",""))
                    passw= passw.replace(" ","")
                    person = Person(name,phone,passw)
                    self.personList.add(person)
    def setInput(self,nameinput):
        self.inputfile = nameinput

#Supposingly the myinput.txt has the following format:
#NAME,PHONE,PASSWORD
readData = ReadData()
readData.Run()
readData.setInput("myfile.txt")
readData.Run()

#per1 = Person("John",3444, 1234 )
#per2 = Person("Mary",3652, 12342)
#perList.add(per1)
#perList.add(per2)
#perList.add(per3)
#perList.Print()
The first class allows you to define persons, giving them name, phones, passwords, or any other kind of field you want. You can also see an operation overloading in that class which allows to check if a person is double counted or not...
The second class is going to store the persons you like. The only thing you have to do is to call the add method of the class on some person object.
The third class is what puts everything in motion, by opening a file that contains the info you want and stores them into the personList as persons...
Of course this is just an illustration (I haven't put much thought on what is happening where), if someone has some comments on my code feel free to speak them :)
 
  • Like
Likes stoomart
  • #7
Thanks for all the replies. I think classes are a bit advanced for us.

We've been doing some reading and we have some prototype code working that uses CSV files and the CSV library. We've got it to the point where we can sort the contents of a CSV file by column or extract a row based on a column etc. This seems to be the level of difficulty they were expected to achieve.
 

1. What is a Python database?

A Python database is a collection of data that is organized and stored in a structured format using the Python programming language. It allows for efficient storage, retrieval, and manipulation of data using Python.

2. How do I create a database in Python?

To create a database in Python, you can use a built-in module called "sqlite3". First, import the module and then create a connection to a database file. Next, create a cursor object to execute SQL commands and use the "execute()" method to create tables and insert data into the database.

3. What is the difference between a relational and non-relational database?

A relational database stores data in a tabular format with rows and columns, and uses a structured query language (SQL) to retrieve data. A non-relational database, also known as a NoSQL database, stores data in a non-tabular format and uses a variety of data models for accessing and organizing data.

4. How do I query data from a Python database?

To query data from a Python database, you can use the "SELECT" statement in SQL. This allows you to specify which columns and rows you want to retrieve from the database. You can also use other SQL clauses such as "WHERE" and "ORDER BY" to filter and sort the data.

5. Are there any other Python modules for working with databases?

Yes, there are several other Python modules for working with databases, such as MySQL, PostgreSQL, and MongoDB. These modules allow you to connect to different types of databases and perform similar operations as the "sqlite3" module.

Similar threads

Replies
7
Views
252
  • Programming and Computer Science
Replies
15
Views
1K
  • Feedback and Announcements
Replies
0
Views
94K
  • STEM Academic Advising
Replies
5
Views
1K
  • Mechanical Engineering
Replies
23
Views
36K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
7
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
7
Views
3K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
7
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
9
Views
2K
Back
Top