67 lines
1.7 KiB
Python
67 lines
1.7 KiB
Python
# PyMySQL - um cliente MySQL feito em Python Puro
|
|
# Doc: https://pymysql.readthedocs.io/en/latest/
|
|
# Pypy: https://pypi.org/project/pymysql/
|
|
# GitHub: https://github.com/PyMySQL/PyMySQL
|
|
import os
|
|
|
|
import dotenv
|
|
import pymysql
|
|
|
|
TABLE_NAME = 'customers'
|
|
|
|
dotenv.load_dotenv()
|
|
|
|
connection = pymysql.connect(
|
|
host=os.environ['MYSQL_HOST'],
|
|
user=os.environ['MYSQL_USER'],
|
|
password=os.environ['MYSQL_PASSWORD'],
|
|
database=os.environ['MYSQL_DATABASE'],
|
|
charset='utf8mb4'
|
|
)
|
|
|
|
with connection:
|
|
with connection.cursor() as cursor:
|
|
cursor.execute( # type: ignore
|
|
f'CREATE TABLE IF NOT EXISTS {TABLE_NAME} ('
|
|
'id INT NOT NULL AUTO_INCREMENT, '
|
|
'nome VARCHAR(50) NOT NULL, '
|
|
'idade INT NOT NULL, '
|
|
'PRIMARY KEY (id)'
|
|
') '
|
|
)
|
|
# CUIDADO: ISSO LIMPA A TABELA
|
|
cursor.execute(f'TRUNCATE TABLE {TABLE_NAME}') # type: ignore
|
|
connection.commit()
|
|
|
|
# Começo a manipular dados a partir daqui
|
|
|
|
with connection.cursor() as cursor:
|
|
sql = (
|
|
f'INSERT INTO {TABLE_NAME} '
|
|
'(nome, idade) '
|
|
'VALUES '
|
|
'(%s, %s) '
|
|
)
|
|
data = ('Luiz', 18)
|
|
result = cursor.execute(sql, data) # type: ignore
|
|
# print(sql, data)
|
|
# print(result)
|
|
connection.commit()
|
|
|
|
with connection.cursor() as cursor:
|
|
sql = (
|
|
f'INSERT INTO {TABLE_NAME} '
|
|
'(nome, idade) '
|
|
'VALUES '
|
|
'(%(name)s, %(age)s) '
|
|
)
|
|
data2 = {
|
|
"age": 37,
|
|
"name": "Le",
|
|
}
|
|
result = cursor.execute(sql, data2) # type: ignore
|
|
print(sql)
|
|
print(data2)
|
|
print(result)
|
|
connection.commit()
|