[PYTHON] Connect to mysql

Use mysql-connector-python

import mysql.connector

conn = mysql.connector.connect(host='127.0.0.1', user='root', password='')
cursor = conn.cursor()

cursor.execute('CREATE DATABASE test_mysql_database')

cursor.close()
conn.close()

conn = mysql.connector.connect(host='127.0.0.1', database='test_mysql_database')
cursor = conn.cursor()
cursor.execute('CREATE TABLE persons('
               'id int NOT NULL AUTO_INCREMENT,'
               'name VARCHAR(14) NOT NULL,'
               'PRIMARY KEY(id))')
cursor.execute('INSERT INTO persons(name) values("Mike")')
conn.commit()

cursor.execute('SELECT * FROM persons')
for row in cursor:
    print(row)

cursor.close()
conn.close()

output:

(1, 'Mike')

Recommended Posts

Connect to mysql
Connect python to mysql
Connect to MySQL using Flask SQLAlchemy
Connect to Docker's MySQL container from Flask
Connect to MySQL with Python within Docker
Connect to MySQL with Python on Raspberry Pi
Connect to BigQuery with Python
Connect to Postgresql with GO
Connect Vagrant's MySQL with MySQL Workbench
Connect to sqlite from python
Connect to s3 tokyo region
I get [Error 2055] when trying to connect to MySQL on Heroku
Script to mysqldump to all MySQL DBs
Steps to install MySQL 8.0 on CentOS 8.1
Connect to utf8mb4 database from python
Misunderstanding on how to connect cnn
How to use Mysql in python
Connect to Elastic MQ with boto
Ssh connect to GCP from Windows
Connect two USB cameras to Raspberry Pi 4
Connect to Packetix VPN from CentOS 7 minimal.
Connect Sipeed Lichee Zero to the net
Connecting from python to MySQL on CentOS 6.4
A story about trying to connect to MySQL using Heroku and giving up
Upgraded mysql on Cloud9 (Amazon Linux) (5.5 to 5,7)
Connect to GNU / Linux with Remote Desktop
Dump SQLite3 data and migrate to MySQL
How to handle consecutive values in MySQL
Connect to s3 with AWS Lambda Python
[Python / Tkinter] Connect keyboard shortcuts to Menu
Connect to pepper with PEPPER Mac's python interpreter
Scraping using lxml and saving to MySQL
How to use SQLAlchemy / Connect with aiomysql
[Note] QXcbConnection: Could not connect to display
Connect to coincheck's Websocket API from Python
Gusto cannot connect to Wifi on Linux
I want to connect to PostgreSQL from various languages
Connect to Supercomputer ITO Jupyter from client browser
Problems connecting to MySQL from Docker environment (Debian)
Easily connect Xillybus to user logic with cReComp
Write a script to convert a MySQL dump to TSV
Connect your Raspberry Pi to your smartphone using Blynk
Connect to the Bitcoin network using pybitcoin tools
Connect to a serial console via Bluetooth (CentOS 7)
Use Tor to connect from urllib2 [Python] [Mac]
[AWS] Migrate data from DynamoDB to Aurora MySQL
[AWS EC2] How to install only MySQL client on Amazon Linux 2 and connect to RDS