





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






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) )
Thêm bản ghi mới with connection.cursor() as cursor:
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:
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()
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)
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'}]
Source: https://www.w3schools.com/sql/sql_join.asp