python mysql处理_python处理MySQL

本文介绍了使用Python的pymysql库进行数据库连接,包括执行SQL查询并处理结果,以及如何利用SQLAlchemy操作DataFrame与MySQL之间的数据交换。涵盖了基本的CRUD操作和DataFrame数据类型映射。
摘要由CSDN通过智能技术生成

import pymysql

# 创建数据库连接

db = pymysql.connect(host="localhost", port=3306, user="root", password="123456", database="stu", charset="utf8")

# 创建游标对象

cur = db.cursor()

sql = "select * from class where gender='m';"

cur.execute(sql)

# 获取一个查询结果

one_row = cur.fetchone()

print(one_row) # 元组

# 获取多个查询结果

many_row = cur.fetchmany(2)

print(many_row) # 元组套元组

# 获取所有查询结果

all_row = cur.fetchall()

print(all_row) # 元组套元组

写操作

try:

sql = "insert into class (name,age,score) values ('%s','%s','%s')" % (name, age, score) # 注:字符串类型%s要加引号

cur.execute(sql)

db.commit()

except Exception as e:

db.rollback() # 退回到commit执行之前的数据库状态

print(e)

# 关闭游标对象

cur.close()

# 关闭数据苦连接

db.close()

DataFrame与mysql交互

from sqlalchemy import create_engine

from sqlalchemy.types import Integer, VARCHAR, Date, DECIMAL

conn = create_engine("mysql+pymysql://username:password@localhost:3306/dbname?charset=utf8")

df.to_sql("表名", con=conn, index=False, if_exists="replace", dtype={

"id":Integer(),

"GMV_date":Date(),

"platform":VARCHAR(length=20),

"GMV_result":DECIMAL(),

"GMV_target":DECIMAL(),

"completion":DECIMAL(precision=7, scale=2, asdecimal=True)

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值