1、使用pymysql
import pymysql
pymysql.install_as_MySQLdb()
#注意:mysqldb是python2中的包,在python3中已经变为pymsql,如果想继续使用python2的数据库连接格式
#可以调用pymysql.install_as_MySQLdb()命令
conn=pymysql.connect(host='192.168.3.88',user='***',passwd='123456',db='***',
port=3306,charset='utf8')
pd.read_sql_table('table_name',con=conn)
注意:使用pymsql可以查询数据库,但是读取数据库表格时会报如下错误:
NotImplementedError: read_sql_table only supported for SQLAlchemy connectable.
也就是只支持使用SQLAlchemy来读取表格。
2、使用sqlalchemy来读取表格
from sqlalchemy import create_engine
if args.sql:
engine=create_engine("mysql://username:password@192.168.3.88:3306/databse",echo=True)
conn=engine.connect()
data_sql=pd.read_sql_table(table_name='table_name',con=conn)
data_sql.to_csv('news.csv')
else:
news_data=pd.read_csv('news.csv',encoding='utf-8')
说明:
- username--用户名
- password--密码
- 192.168.3.88:3306--地址以及端口号
- databse--数据库名
3、注意命令解析库argparse的用法,这个比较好用,方便代码debug:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--sql',action='store_true',default=False,help='whether get news_data from MySQL')
parser.add_argument('--summary',action='store_true',default=False,help='whether to train news_summary_info')
parser.add_argument('--author',action='store_true',default=True,help='whether to train news_author')
parser.add_argument('--redactor',action='store_true',default=False,help='whether to train news_redactor')
parser.add_argument('--keyword',action='store_true',default=False,help='whether to train news_keyword')
args=parser.parse_args()