01. To Get Started
overview
- Python is a computer language, used for many applications.
- In this topic, the database application will be discussed.
- The application is in one tier, the database server is in another tier.
- Python can be used for many different database types, like msql,...
My development environment
- mac
- python 3
- Code visual studio is used the develop IDE.
- Using any IDE is an option.
It has three windows.
- code editor
- terminal. It is use to run the application.
- folder explorer
The following steps is to have the environment ready.
- To begin with, launch Anaconda navigator.
- Many packages are used in one python file or one python application. Anacode is to manage them.
- launch code vs.
- In mac menu, select file|open, select a folder.
- You'll see the explorer window is open.
- in the explorer, select the folder, click icon to add a foler.
- click it, create a folder for this application, name peterapp1.
- in the mac menu, clcik terminal, then, click new terminal.
- cd peterapp1, pwd to confirm it.
- In the explorer, with folder peterapp1 selected, click the icon to add a file, test1.py.
- The editer window is open. Type print("Hi, I am ready")
- In the terminal, enter python --version. Python 2.7.14 is return.
- alias python=python3
- enter pwd, the version is 3.7.12 now.
- python test1.py
- See the output, "Hi, I am ready."
Python is an interpreted language. It makes developing more easy.
- The following is to demonstrate this point.
- create a file test2.py as below:
----- code -----
sum = 0
mylist = [1,2,3,4,5]
for x in mylist:
sum += x
print(sum)
----- test ------
$python
>>> sum = 0
>>> mylist = [1,2,3,4,5]
>>> for x in mylist:
--- sum += x
hit enter
>>> print(sum)
15
exit()
$
----- comments ---------
You execute one line at a time, including compilation and execution.
The variables like sum, mylist are in the memory until you execute exit command.
02. Using Python for MySql
Descriptions
- The learning materials is from w3cshools.com/python
- There are three ways to test.
- First, you can test in w3c website with the provided code..
- Second, you can have your own mysql server on your machine.
- install mysql
- In your machine, launch an additional command window.
- start your mysqol server.
- note 1: make sure python3 is for all the command windows.
- note 2: Ctrl_c to shut down the server.
- Third way is to use external mysql service provider.
- I use this way.
- My website provider provides mysql service.
- I created my database over there.
- Four pieces data are required as below
- host="my05.winhost.com"
- user="xxxxxx"
- password="xxxxxx"
- database="mysql_55668_mydatabase"
- These are used in the database tier, they are not referred in your python code.
- The database has an address.
- MySql is relational database.
- Sqlite is relational database also.
- Python language provides the database processing code.
- No additional process thread needed.
- Django package, Django uses it as default database.
- It is mostly for mobile apps.Swift language is for ios. Java is for Android.
- It is stored in files.
Install and test mysql driver for python
- MS window environment is used
- In code vs, open its terminal window.
- pip list, see mysql-connector, not mysql-connector-python
- mysql-connector is for other language, not python.
- First, install the package, mysql-connector-python.
- pip list again, see mysql-connector-python
- create a python file, test_connector.py
- add one line import mysql.connector
- note: mysql.connector is a module name.
- python test_connector.py,
- If the above code was executed with no errors, "MySQL Connector" is installed correctly.
Create a mysql database
- I used a commercial mysql db provider, not in my local machine.
- Over there, I added a mysql database.
- Take notes the following information
- mysql server name
- the database name
- user name for the database
- password for the database
- Then, created a file, test_mysql_2.py to verify.
import mysql.connector
mydb = mysql.connector.connect(
host="my05.winhost.com",
user="xxxxxx",
password="xxxxxxxx",
database="mysql_55668_mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
test and analyze the database creation
- python test_mysql_2.py
- the database name is returned.
- Cursor objects interact with the MySQL server
- Cursor is like a proxy for the database tier.
- In the following line, it makes the request for the list of my databases in the server.
- API mycursor.execute("SHOW DATABASES") is to make db call for all the databases.
- Each loop, the server returns a tuple with one item like ('mysql_55668_mydatabase',)
- Examining the mechanism for mycursor.execute("SHOW DATABASE")
- the control is passed into the database tier.
- then, the control returns to the app tier. The return data containing database names.
- update the cursor, containing list data structure.
Create Table
- mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
- The argument is sql code. The column type, like VARCHAR, is sql column type.
- If pk is required, add one column, id INT AUTO_INCREMENT PRIMARY KEY, before name, address.
- Each column type has its implicit default.
- for type INT for any columns
- The impicit content is 0, which will be stored in the database.
- In the next topic, CRUD, when reading table users, column fav will be 0 when it is empty.
- When you want get the record from database. You can use code as below:
- select ..., NULLIF(myint, 0) as myint2.
- Column myint with type INT with 0 value, myint2 is an new column, its value is null.
- This way makes you feel more make sense.
CRUD
- The api used for mysql CRUD apply sql statements.
- No python dictionary is used for setting up conditions like mongodb.
Table Join
- Why many tables?
- The content structure is more flexible - inner join,left join,right join...
- Save disk and memory space.
- tables for joins
- Two tables are involved.
- Child table is products
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }
create it FIRST and add 3 records.
- Parent table is users.
{ id: 1, name: 'John', fav: 154},
{ id: 2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}
- Prepare the child table, products first.
- It has two columns. Column id is PK. column name describes the products.
- The child table is for referred.
- Then, prepare the parent table, users.
- It has three columns. Column id is PK. Column name is user name. Column fav is the product id.
- No foreign key constraint is set for this senarios for empty data for fav.
- inner join
-
...... code ......
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
users.id AS userid, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
- output as below
('John', 1, 'Chocolate Heaven')
('Peter', 2, 'Chocolate Heaven')
('Amy', 3, 'Tasty Lemons')
- "\" is for python line continuation.
- Join is for column content matches.
- The column in the parent table, users, is fav.
- The column in the child table, products, is id, PK
- First, to get the data for the match in the database tier.
- Then, back to the python app tier to update the cursor.
- Finally, in the curor, select the output and render them.
- In this case, there are 3 matches.
- They are presented in tuple, python collection data structure to present an entity.
- The second in one tuple is automatically set to python integer from Sql data type.
- In this python database application, no data model class is required.
- left join, right join
- The parent table is considered on the left hand side.
- The child table is considered on the right hand side.
- left join
- For code, change "INNER JOIN" to "LEFT JOIN".
- The result of output as below:
In addition to the 3 tuples for match,
Two other rows in parent table with no match is output also.
('Hannah', 4, None)
('Michael', 5, None)
- Sometimes, it is required from application perspective.
- right join
- For code, change "INNER JOIN" to "RIGHT JOIN".
- The result of output as below:
In addition to the 3 tuples for match,
One other row in child table with no match is output also.
(None, None, 'Vanilla Dreams')
- Sometimes, it is required from application perspective.
03. Using Python for Sqlite
overview
- Sqlite, like mysql, is relational database.
- When you have only one python file, Sqlite code is included.
- There is no need for a server in a different processing thread. It is is EASY.
- The database is stored in a file under the same folder. It is MOBILE.
- Mobile apps use sqlite using swift for ios and Java for Android for its simplicity. So does Python code.
- There are always little different among different database types, like mysql, sqlite...
- For example, there is no built-in right join for sqlite.
- But, you can find someway to get around from web.
- Django is the package for Python web server. It is use sqlite as default.
There are only a few lines of code needed.
using sqlite in python.
--- lab 1. test python module sqlite3-------------------------
* create a folder, myfolder, and make sure pythons' version is 3.
* create a file, myfile.py, enter one line
import sqlite3
* enter python myfile.py
* if no break, to confirm python module sqlite3 can be accessed.
--- lab 2. create a database in a files
* enter the 2nd line as below:
conn = sqlite3.connect('Test.db')
* If the database does not exist, it will be created.
* And the database file will be created under folder myfolder.
* variable conn wil be created for further use.
--- lab 3. create table and insert records
c = conn.cursor()
#Droping users table if already exists
c.execute("DROP TABLE IF EXISTS users")
print("Table dropped... ")
#create table
sql = "CREATE TABLE uSers(id integer pRIMARY KeY,namE varchar, fav inT)"
c.execute(sql)
c.execute('''INSERT INTO users(
id, name, fav) VALUES(1,'Peter', 369)''')
c.execute('''INSERT INTO users(
ID, NAME, fav) VALUES(2,'Tairo', 123)''')
c.execute('''INSERT INTO users(
Id, name, FAV) VALUES(3,'Emi', 911)''')
#commit the changes to db
conn.commit()
#close the connection
conn.close()
print("table users created, insert 3 record")
code analysis
- c = conn.cursor()
The connection object uses cursor method to create a cursor object.
The cursor object does the following things:
- connect to database scope. For sqlite, it is in the memory of the same device.
- issue the requests to the database
- receive the results and store them within the cursor.
- fetch data within the cursor.
- The code executed in the database scope
- They are not case sensitive.
- The syntax is bit loose. For example, you can use either INT, INTERGER, int, interger.
- Primary Key
- Here, I manually provide the values.
- If you want use AUTO_INCREMENT feature, you have to go to web to find some help to do so.
- table joins
- sqlite3 supports inner join and left join.
- If you want use right join, you have to go to web to find some help to do so.
- conn.commit()
- after the above code, the database is updated, and persists in the file.
--- lab 4. fetch data -------------------------
import sqlite3
conn = sqlite3.connect('Test.db')
c = conn.cursor()
c.execute("SELECT * FROM users")
rows = c.fetchall()
for row in rows:
print(row)
conn.close()
- create another file myfile2.py using the above code.
- in the command shell, enter python myfile2.py
- You'll see 3 records.
Using Sqlite in Django
- Django is a high-level Python web framework.
- When a new project is created, settings.py is created.
- In its database section, you can see default is sqlite3, the new database name is db.sqlite3.
- Django supports MVC structure. Synchronous activities happen between models and views.
- After a project is created, create an application.
- Under the application folder, there is a models.py
- A models module contains model classes, in which their columns are defined in python.
- Then, you use a command with makemigrations to prepare the scripts for propagating the schema.
- Then, you use a command with migrate to create table schemas in the dababase.
- MySql uses sql statements to define table schemas.
- Automatically the MVC structure support read, update, delete...
- The sqlite databases has many other tables to support auth, session...