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()

最新文章

  1. react+redux教程(七)自定义redux中间件
  2. js cookie
  3. 1Z0-053 争议题目解析505
  4. [Linux 存储管理] LVM结构
  5. Mybatis根据表自动生成相关代码
  6. nginx(五)nginx与php的安装配置
  7. Show All Running Processes in Linux
  8. 黑马程序员-for和foreach
  9. ASP.NET页面错误处理
  10. javascript 数据结构和算法读书笔记 > 第一章 javascript的编程环境和模型
  11. poj3207(two-sat)
  12. Java EE (3) -- Java EE 6 Web Services Developer Certified Expert(1z0-897)
  13. zookeeper入门知识
  14. Self referencing loop detected for property 错误
  15. Linux下的Mysql数据库备份+还原
  16. Flask核心机制--上下文源码剖析
  17. 关于 Data URI Scheme -- data:image/jpg;base64
  18. gym 101164 H.Pub crawl 凸包
  19. vlookup返回多个结果
  20. 团体程序设计天梯赛 L2-016. 愿天下有情人都是失散多年的兄妹

热门文章

  1. 数据分析与展示---Matplotlib入门
  2. 安装lsb_release
  3. vue 脚手架使用
  4. 如何在Windows系统下隐藏文件
  5. SpringBoot 线程池配置 实现AsyncConfigurer接口方法
  6. 2019年湖南多校第一场||2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018)
  7. [Openwrt扩展中篇]添加Aria2和webui
  8. mysql 增加字段脚本,以及删除主键约束的脚本,存储过程
  9. curator框架的使用以及实现分布式锁等应用与zkclient操作zookeeper,简化复杂原生API
  10. 【FCS NOI2018】福建省冬摸鱼笔记 day5