python3与mysql交互:pymysql
2024-08-26 16:53:45
python3与mysql交互
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='192.168.26.131',
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()
最新文章
- react+redux教程(七)自定义redux中间件
- js cookie
- 1Z0-053 争议题目解析505
- [Linux 存储管理] LVM结构
- Mybatis根据表自动生成相关代码
- nginx(五)nginx与php的安装配置
- Show All Running Processes in Linux
- 黑马程序员-for和foreach
- ASP.NET页面错误处理
- javascript 数据结构和算法读书笔记 >; 第一章 javascript的编程环境和模型
- poj3207(two-sat)
- Java EE (3) -- Java EE 6 Web Services Developer Certified Expert(1z0-897)
- zookeeper入门知识
- Self referencing loop detected for property 错误
- Linux下的Mysql数据库备份+还原
- Flask核心机制--上下文源码剖析
- 关于 Data URI Scheme -- data:image/jpg;base64
- gym 101164 H.Pub crawl 凸包
- vlookup返回多个结果
- 团体程序设计天梯赛 L2-016. 愿天下有情人都是失散多年的兄妹
热门文章
- 数据分析与展示---Matplotlib入门
- 安装lsb_release
- vue 脚手架使用
- 如何在Windows系统下隐藏文件
- SpringBoot 线程池配置 实现AsyncConfigurer接口方法
- 2019年湖南多校第一场||2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018)
- [Openwrt扩展中篇]添加Aria2和webui
- mysql 增加字段脚本,以及删除主键约束的脚本,存储过程
- curator框架的使用以及实现分布式锁等应用与zkclient操作zookeeper,简化复杂原生API
- 【FCS NOI2018】福建省冬摸鱼笔记 day5