The data obtained by using the PyMySQL package is in the format of tuples or dictionaries. If further processing is required, it needs to be converted into the DataFrame format of pandas, which is troublesome.
And directly using the read_sql_query() function of pandas can directly get the data in DataFrame format, and can also add, delete, modify and query the table
Note that in addition to PyMySQL and pandas, you also need to install the SQLAlchemy package
Basic query operations:
import pymysql
import pandas as pd
import sqlalchemy
con=sqlalchemy.create_engine('mysql+pymysql://root:[email protected]:3306/question?charset=utf8')
#创建数据库的连接引擎
dt=pd.read_sql_query(sql='select * from question.q_info',con=con,index_col=['id'])
#根据SQL读取数据
print(dt)
operation result:
The read_sql_query() function has some other parameters:
coerce: Attempt to convert non-string and non-numeric objects into floating-point numbers, the default is True
params: It can be a list, dictionary, or tuple, used to store variables for dynamically splicing SQL commands
parse_dates: parse the specified field into a date format
chunksize: If not set, a DataFrame object is returned
increase data
import pymysql
import pandas as pd
import sqlalchemy
con=sqlalchemy.create_engine('mysql+pymysql://root:[email protected]:3306/question?charset=utf8')
#创建数据库的连接引擎
pd.read_sql_query(sql="insert into question.q_info values(8,'zsgvdx','不服从部分')",con=con)
#增加数据
dt=pd.read_sql_query(sql='select * from question.q_info',con=con,index_col=['id'])
#根据SQL读取数据
print(dt)