码迷,mamicode.com
首页 > 数据库 > 详细

python3与mysql交互

时间:2018-12-19 15:54:05      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:port   cep   def   交互   function   connect   shel   obj   mys   

 

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=‘localhost‘,
                port=3306,
                user=‘root‘,
                passwd=‘12345678‘,
                db=‘test‘,
                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交互

标签:port   cep   def   交互   function   connect   shel   obj   mys   

原文地址:https://www.cnblogs.com/drizzle-xu/p/10142914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!