首页 / PYTHON / python3与mysql交互
python3与mysql交互
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python3与mysql交互,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1219字,纯文字阅读大概需要2分钟。
内容图文
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()
内容总结
以上是互联网集市为您收集整理的python3与mysql交互全部内容,希望文章能够帮你解决python3与mysql交互所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。