python3与mysql交互

本文详细介绍如何使用Python的pymysql模块连接并操作MySQL数据库。包括创建数据库表、插入数据、修改记录、删除数据及查询等功能,通过具体代码实现,帮助读者快速掌握pymysql的基本用法。
1.安装pymysql模块
pip3 install pymysql3

2.pymysql的简单使用:
# /usr/bin/env python3
import pymysql


class Mysql(object): def __init__(self): try: self.conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd='mysql', db='testdb', charset='utf8' ) except Exception as e: print(e) else: print('连接成功') self.cur = self.conn.cursor() def create_table(self): sql = 'create table testtb(id int, name varchar(10),age int)' res = self.cur.execute(sql) print(res) def close(self): self.cur.close() self.conn.close() def add(self): # 增 sql = 'insert into testtb values(1,"Tom",18),(2,"Jerry",16),(3,"Hank",24)' res = self.cur.execute(sql) if res: self.conn.commit() else: self.conn.rollback() print(res) def rem(self): # 删 sql = 'delete from testtb where id=1' res = self.cur.execute(sql) if res: self.conn.commit() else: self.conn.rollback() print(res) def mod(self): # 改 sql = 'update testtb set name="Tom Ding" where id=2' res = self.cur.execute(sql) if res: self.conn.commit() else: self.conn.rollback() print(res) def show(self): # 查 sql = 'select * from testtb' self.cur.execute(sql) res = self.cur.fetchall() for i in res: print(i) if __name__ == "__main__": mysql = Mysql() mysql.create_table() mysql.add() mysql.mod() mysql.rem() mysql.show() mysql.close()

转载于:https://www.cnblogs.com/yunlongaimeng/p/10438340.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值