jupyter notebook读取mysql数据库

一、首先安装pymysql驱动

1.打开Anaconda 命令窗口:Anaconda Prompt (anaconda3)

2.安装pymysql:pip install pymysql

二、打开 jupyter notebook进行数据库操作

1.首先导入pandas 和sqlalchemy

import pandas as pd
import sqlalchemy as sqla

# 创建连接:root后输mysql数据库密码,@后输入mysql ip地址,斜杠后输数据库名
db = sqla.create_engine('mysql+pymysql://root:password@ip/databaseName?charset=utf8') 
db

2.连接数据库是可能会报错:1130, "Host 'xxxx' is not allowed to connect to this MySQL server",需要在数据库中给所有远程用户授权

# 在数据库中执行以下命令,给所有远程用户授权
update user set host='%' where user='root'; 

# 执行授权后刷新权限信息
flush privileges;

3.接下来就可以连接并读取数据库了

# 列出数据库中的所有表
formlist = pd.read_sql_query('show tables',con=db)
print(formlist)

# 查看某张表中的数据
table1= pd.read_sql_table('tableName',con=db)
table1

# 使用sql语句查询某张表
result = pd.read_sql('select * from tableName ',con=db)
result

猜你喜欢

转载自blog.csdn.net/qq_29644709/article/details/107284072