python连接数据库

-- coding: utf-8 --

导入必要模块

import pandas as pd

from sqlalchemy import create_engine

初始化数据库连接,使用pymysql模块

MySQL的用户:root, 密码:147369, 端口:3306,数据库:mydb

engine = create_engine('mysql+pymysql://root:147369@localhost:3306/mydb')

查询语句,选出employee表中的所有数据

sql = '''

select * from employee;

'''

read_sql_query的两个参数: sql语句, 数据库连接

df = pd.read_sql_query(sql, engine)

输出employee表的查询结果

print(df)

新建pandas中的DataFrame, 只有id,num两列

df = pd.DataFrame({'id':[1,2,3,4],'num':[12,34,56,89]})

将新建的DataFrame储存为MySQL中的数据表,不储存index列

df.to_sql('mydf', engine, index= False)

print('Read from and write to Mysql table successfully!')

相关推荐
方璧3 小时前
限流的算法
java·开发语言
Hi_kenyon4 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
曲莫终4 小时前
Java VarHandle全面详解:从入门到精通
java·开发语言
ruleslol4 小时前
MySQL的段、区、页、行 详解
数据库·mysql
Learn-Python4 小时前
MongoDB-only方法
python·sql
while(1){yan}4 小时前
MyBatis Generator
数据库·spring boot·java-ee·mybatis
それども4 小时前
MySQL affectedRows 计算逻辑
数据库·mysql
ghie90904 小时前
基于MATLAB GUI的伏安法测电阻实现方案
开发语言·matlab·电阻
Gao_xu_sheng4 小时前
Inno Setup(专业安装/更新 EXE)
开发语言