python connect to mysql database and read data
1. Install the pymysql package
pip install pymysql
Note:
- MySQLdb only supports python2, pymysql supports python3
2. Connect data
import pymysql
import pandas as pd
from pandas import DataFrame as df
conn = pymysql.Connect(
host = 'IP地址',
port = 端口号,
user = '用户名',
passwd = '用户密码',
db = '数据库名称',
charset = 'utf8'
)
Note:
- View the local IP address: cmd input: ipconfig, IPv4 address
- The host server address in the pymysql.Connect parameter, this machine can be'localhost'
3. Read the data
(1) Use read_sql to read data
sql = 'select * from testa'
data = pd.read_sql(sql, conn)
(2) Use cursor to read data
sql = 'select * from testa'
cur = conn.cursor()
try: # 使用异常处理,以防程序无法正常运行
cur.execute(sql)
data = df(cur.fetchall(), columns = [col[0] for col in cur.description])
except Exception as e:
conn.rollback() # 发生错误时回滚
print('事务处理失败', e)
else:
# conn.commit() # 事务提交
print('事务处理成功', cur.rowcount)
cur.close()
Note:
-
The difference between read_sql and cursor cursor:
read_sql: can only execute query data
cursor cursor: can execute query, insert, update, delete and other operations -
cur.execute(sql):
Execute specific database operations -
cur.fetchone():
get a single piece of data
cur.fetchmany(3):
get the first 3
pieces of data cur.fetchall():
get all data -
Field names are included in the query results:
# 法1: cur = conn.cursor(cursor = pymysql.cursors.DictCursor) # 设置成DictCursor,结果包含字段名称 cur.execute(sql) data = df(cur.fetchall()) # 法2: cur = conn.cursor() cur.execute(sql) data = df(cur.fetchall(),columns = [col[0] for col in cur.description])
-
conn.commit():
This statement is required for operations such as insert, update, and delete; it is not required for querying, creating databases, and data tables -
cur.rowcount:
Returns the number of operations performed
4. Close the database
conn.close()