Docsity

Python Backend with MySQL: Setup, Connect, Add, Select, Join, Summaries of Mathematics

Partial preview of the text

Download Python Backend with MySQL: Setup, Connect, Add, Select, Join and more Summaries Mathematics in PDF only on Docsity!

Lập trình hệ thống backend

với Python

Phí Hoàng Anh

Cài đặt thư viện

Cài đặt thư viện: pip install pymysql Tạo 1 database: CREATE TABLE user ( id INTEGER NOT NULL, email VARCHAR, password VARCHAR, PRIMARY KEY (id), UNIQUE (email) )

Add, Select

Thêm bản ghi mới with connection.cursor() as cursor:

Tạo bản ghi mới

sql = "INSERT INTO users (email, password) VALUES (%s, %s)" cursor.execute(sql, ('[email protected]', 'very-secret')) connection.commit() Đọc bản ghi: with connection.cursor() as cursor:

Đọc 1 bản ghi

sql = "SELECT id, password FROM users WHERE email = %s and password = %s" cursor.execute(sql, ('[email protected]', 'very-secret')) result = cursor.fetchone() print(result) # {'email': '[email protected]', 'password': 'very-secret'} connection.close()

Select / Insert với nhiều bản ghi

Lấy về tất cả bản ghi: result = cursor.fetchall() # [{'email': '[email protected]', 'password': 'very-secret'}] Update nhiều bản ghi: data = [ ('Jane', “Jane ‘s password”), ('Joe', “Joe ‘s password”), ('John', “John ‘s password”), ] stmt = "INSERT INTO users (email, password) VALUES (%s, %s)" cursor.executemany(stmt, data)

Join tables

Tạo thêm 1 bảng sau:

CREATE TABLE images ( id INTEGER NOT NULL, image_path VARCHAR, email VARCHAR, PRIMARY KEY (id) ) sql = “INSERT INTO images (email, image_path) VALUES (‘[email protected]’, ‘my_first_image’)” cursor.execute(sql) connection.commit() sql = “SELECT users.email, users.password FROM users INNER JOIN images ON users.email=images.email” cursor.execute(sql) # [{'email': '[email protected]', 'password': 'very-secret'}]

Join tables

Source: https://www.w3schools.com/sql/sql_join.asp