Python连接MySQL数据库(pymysql),DataFrame写入 MySQL(create_engine)- Python代码

版权声明:转载请联系作者,获得允许后,添加链接及作者到页首 https://blog.csdn.net/weixin_40683253/article/details/86741134

模块安装

使用以下命令安装 PyMySQL:

$ pip install PyMySQL

若系统不支持 pip,还可以这样安装:

$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install

Python连接MySQL数据库

# -*- coding:utf-8 -*-
import pymysql 
import pandas as pd
from pandas import DataFrame,Series

# 打开数据库连接(host一般都是localhost,user填写用户名,password是密码,port一般也是3306)
db = pymysql.connect(host='localhost', user='root', password='******', port=3306) 

cursor = db.cursor() #获取游标
data = cursor.execute("SELECT * FROM ajx.zhibiao")# 执行SQL查询,获取数据
data = list(cursor.fetchall())# 获取单条数据
db.close()# 关闭数据库连接

#获取的数据存入本地(也可在下面的模型中直接使用 data )
re_outfile =  u'D:\\pythondata\\re_zhibiao.xlsx'
data_re.to_excel(re_outfile)
print(u'数据读取结束,并保存至本地:', str(outputfile))

如果还需要获取到列名,需要加一句了:

# -*- coding:utf-8 -*-
import pymysql 
import pandas as pd
from pandas import DataFrame,Series

# 打开数据库连接(host一般都是localhost,user填写用户名,password是密码,port一般也是3306)
db = pymysql.connect(host='localhost', user='root', password='******', port=3306) 

# 获取数据
cursor = db.cursor() #获取游标
data = cursor.execute("SELECT * FROM ajx.zhibiao")# 执行SQL查询,获取数据
data = list(cursor.fetchall())# 获取单条数据

# 获取列名列表
# ################################################相对上一段代码有改动的地方
fea = cursor.execute("SHOW FULL COLUMNS FROM ajx.zhibiao")#获取列名
fea = list(cursor.fetchall())
lis=[]
for i in fea:
    lis.append(list(i)[0])
data = pd.DataFrame(data,columns=lis)#list转化成dataframe格式
columns = data.columns.values.tolist() 
# #######################################################################

db.close()# 关闭数据库连接

#获取的数据存入本地(也可在下面的模型中直接使用 data )
re_outfile =  u'D:\\pythondata\\re_zhibiao.xlsx'
data_re.to_excel(re_outfile)
print(u'数据读取结束,并保存至本地:', str(outputfile))

如果在所有的列中,你只需要获取列名中含有特定字符的列,那么就是这样来实现:

# -*- coding:utf-8 -*-
import pymysql 
import pandas as pd
from pandas import DataFrame,Series

# 打开数据库连接(host一般都是localhost,user填写用户名,password是密码,port一般也是3306)
db = pymysql.connect(host='localhost', user='root', password='******', port=3306) 

# 获取数据
cursor = db.cursor() #获取游标
data = cursor.execute("SELECT * FROM ajx.zhibiao")# 执行SQL查询,获取数据
data = list(cursor.fetchall())# 获取单条数据

# 获取列名列表
fea = cursor.execute("SHOW FULL COLUMNS FROM ajx.zhibiao")#获取列名
fea = list(cursor.fetchall())
lis=[]
for i in fea:
    lis.append(list(i)[0])
data = pd.DataFrame(data,columns=lis)#list转化成dataframe格式
columns = data.columns.values.tolist() 

db.close()# 关闭数据库连接


#获取列名中包含特定字符的列
# #################################相对上一段代码有改动的地方
col_re = []  # 存储包含‘re’字段的列名
for i in columns:
    if 're' in i:
        col_re.append(i)
data_re = data[col_re]  # 根据列名取列
data_re = DataFrame(data_re) # 转化为DataFrame格式
# ##################################################


#获取的数据存入本地(也可在下面的模型中直接使用 data )
re_outfile =  u'D:\\pythondata\\re_zhibiao.xlsx'
data_re.to_excel(re_outfile)
print(u'数据读取结束,并保存至本地:', str(outputfile))

Python  DataFrame写入 MySQL

import pandas as pd
from sqlalchemy import create_engine

#获取到dataframe格式的数据
datafile = u'D:\\pythondata\\learn\\split.xlsx'
data = pd.read_excel(datafile)

#填写链接信息
engine = create_engine("mysql+pymysql://【此处填用户名】:【此处填密码】@【此处填host】:【此处填port】/【此处填数据库的名称】?charset=utf8") 
# 例如:engine = create_engine("mysql+pymysql://root:666666@localhost:3306/ajx?charset=utf8")

#开始写入
data.to_sql(name = 'split',con = engine,if_exists = 'append',index = False,index_label = False)

DataFrame.to_sqlnameconschema = Noneif_exists ='fail'index = Trueindex_label = Nonechunksize = Nonedtype = Nonemethod = None 

name:表名;

if_exists : {'fail','replace','append'},默认'fail'。代表如果name表已存在,则如何操作。

  • if_exists ='fail':若表存在,则报错;
  • if_exists ='replace':若表存在,则删除表中数据重新导入;
  • if_exists ='append':若表存在,则保留表中数据,并将新数据插入;

这两个是关键参数,其他参数的解释可以参考文档:

http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html

猜你喜欢

转载自blog.csdn.net/weixin_40683253/article/details/86741134