# Stor1 See [corresponding PHP](/db/mysql/php/basics1). ## Connect We have a user `stor1` with password `stor1` ```python import mysql.connector host = "127.0.0.1" port = 3306 user = "stor1" password = "stor1" database = "stor1" mydb = mysql.connector.connect( host=host, user=user, password=password, database=database ) cursor = mydb.cursor() ``` ## Insert We presume we have a database `stor1` with table `stor1_01` with the schema ``` +-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | MUL | NULL | | | data | blob | YES | | NULL | | | date | datetime | YES | | NULL | | +-------+--------------+------+-----+---------+----------------+ ``` ```python from datetime import datetime from gen_test_data import gen_test_data table = "stor1_01" def insert(k,v): now = datetime.now() if type(v) is str: v = v.encode() sql = f"INSERT INTO {table} (name, data, date) VALUES (%s, %s, %s)" val = (k,v,now.strftime('%Y-%m-%d %H:%M:%S')) cursor.execute(sql, val) data = gen_test_data() for k,v in data: insert(k,v) mydb.commit() ``` ### And retrieve ```python cursor.execute(f"SELECT name, date, data FROM {table}") for x in cursor: name, date, data = x print(f"{name} {date} -- {len(data)} bytes") ```