Cette méthode a fonctionné pour moi lors de l'ajout de données aléatoires à la table MySql à l'aide d'un script python.
Installez d'abord les packages suivants à l'aide des commandes ci-dessous
pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random
from datetime import date
start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="your_db_name"
)
mycursor = mydb.cursor()
sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
#generate a random date
random_day = date.fromordinal(random.randint(start_dt, end_dt))
value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
mycursor.execute(sql_insertion , value)
mydb.commit()
print("customer records inserted!")
Voici un exemple de sortie de l'insertion
cid | name | email | address | dateJoined |
1 | customer1 | customer_email1 | customer_address1 | 2020-11-15 |
2 | customer2 | customer_email2 | customer_address2 | 2020-10-11 |
3 | customer3 | customer_email3 | customer_address3 | 2020-11-17 |
4 | customer4 | customer_email4 | customer_address4 | 2020-09-20 |
5 | customer5 | customer_email5 | customer_address5 | 2020-02-18 |
6 | customer6 | customer_email6 | customer_address6 | 2020-01-11 |
7 | customer7 | customer_email7 | customer_address7 | 2020-05-30 |
8 | customer8 | customer_email8 | customer_address8 | 2020-04-22 |
9 | customer9 | customer_email9 | customer_address9 | 2020-01-05 |
10 | customer10 | customer_email10| customer_address10| 2020-11-12 |