TRUNCATE e INSERT p/ limpar e criar valores na tabela com um ou mais cursores
This commit is contained in:
@@ -7,6 +7,8 @@ import os
|
|||||||
import dotenv
|
import dotenv
|
||||||
import pymysql
|
import pymysql
|
||||||
|
|
||||||
|
TABLE_NAME = 'customers'
|
||||||
|
|
||||||
dotenv.load_dotenv()
|
dotenv.load_dotenv()
|
||||||
|
|
||||||
connection = pymysql.connect(
|
connection = pymysql.connect(
|
||||||
@@ -14,16 +16,37 @@ connection = pymysql.connect(
|
|||||||
user=os.environ['MYSQL_USER'],
|
user=os.environ['MYSQL_USER'],
|
||||||
password=os.environ['MYSQL_PASSWORD'],
|
password=os.environ['MYSQL_PASSWORD'],
|
||||||
database=os.environ['MYSQL_DATABASE'],
|
database=os.environ['MYSQL_DATABASE'],
|
||||||
|
charset='utf8mb4'
|
||||||
)
|
)
|
||||||
|
|
||||||
with connection:
|
with connection:
|
||||||
with connection.cursor() as cursor:
|
with connection.cursor() as cursor:
|
||||||
cursor.execute( # type: ignore
|
cursor.execute( # type: ignore
|
||||||
'CREATE TABLE IF NOT EXISTS customers ('
|
f'CREATE TABLE IF NOT EXISTS {TABLE_NAME} ('
|
||||||
'id INT NOT NULL AUTO_INCREMENT, '
|
'id INT NOT NULL AUTO_INCREMENT, '
|
||||||
'nome VARCHAR(50) NOT NULL, '
|
'nome VARCHAR(50) NOT NULL, '
|
||||||
'idade INT NOT NULL, '
|
'idade INT NOT NULL, '
|
||||||
'PRIMARY KEY (id)'
|
'PRIMARY KEY (id)'
|
||||||
') '
|
') '
|
||||||
)
|
)
|
||||||
print(cursor)
|
# 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:
|
||||||
|
cursor.execute( # type: ignore
|
||||||
|
f'INSERT INTO {TABLE_NAME} '
|
||||||
|
'(nome, idade) VALUES ("Luiz", 25) '
|
||||||
|
)
|
||||||
|
cursor.execute( # type: ignore
|
||||||
|
f'INSERT INTO {TABLE_NAME} '
|
||||||
|
'(nome, idade) VALUES ("Luiz", 25) '
|
||||||
|
)
|
||||||
|
result = cursor.execute( # type: ignore
|
||||||
|
f'INSERT INTO {TABLE_NAME} '
|
||||||
|
'(nome, idade) VALUES ("Luiz", 25) '
|
||||||
|
)
|
||||||
|
print(result)
|
||||||
|
connection.commit()
|
||||||
|
|||||||
Reference in New Issue
Block a user