42 lines
943 B
Python
42 lines
943 B
Python
import mysql.connector
|
|
|
|
#pip3 install mysql-connector-python
|
|
|
|
#pip install mysql
|
|
#pip install MySQL-python
|
|
#import MySQLdb
|
|
|
|
try:
|
|
conn = mysql.connector.connect(host="localhost",user="root",password="sncfp1p2", database="python")
|
|
cursor = conn.cursor()
|
|
|
|
# créer une table
|
|
cursor.execute("""
|
|
CREATE TABLE IF NOT EXISTS visiteurs (
|
|
id int(5) NOT NULL AUTO_INCREMENT,
|
|
name varchar(50) DEFAULT NULL,
|
|
age INTEGER DEFAULT NULL,
|
|
PRIMARY KEY(id)
|
|
);
|
|
""")
|
|
|
|
# ajouter des données
|
|
user = ("bruno", "50")
|
|
sql = "INSERT INTO visiteurs (name, age) VALUES(%s, %s)"
|
|
|
|
#cursor.execute("""INSERT INTO visiteurs (name, age) VALUES(%s, %d)""", user)
|
|
cursor.execute(sql, user)
|
|
|
|
user = {"name": "olivier", "age" : "34"}
|
|
cursor.execute("""INSERT INTO visiteurs (name, age) VALUES(%(name)s, %(age)s)""", user)
|
|
|
|
conn.commit()
|
|
|
|
except Exception as e:
|
|
print("Erreur")
|
|
conn.rollback()
|
|
# raise e
|
|
|
|
finally:
|
|
conn.close()
|
|
|