zoukankan      html  css  js  c++  java
  • python3与mysql交互:pymysql

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

  • 相关阅读:
    OSPF综合实验一
    OSPF—开放最短路径优先协议详解---附:OSPF LSA 详解
    OSPF--LSA详解
    smfony设置量表之间的关系
    smyfony2 增删改查
    js中substring和substr的用法
    jQuery id模糊 选择器 批量处理
    《内存数据库和mysql的同步机制》
    linux 基本。。
    Django之模板引擎(母版)
  • 原文地址:https://www.cnblogs.com/PrettyTom/p/6880639.html
Copyright © 2011-2022 走看看