python常用库之pymysql对mysql的操作

cfn
2021-01-07
442

安装

pip install pymysql

查询数据

# -*- coding: utf-8 -*- import pymysql from app.toolkit.env import * con = pymysql.connect(host=env("DATABASE", "HOSTNAME"), port=int(env("DATABASE", "HOSTPORT")), user=env("DATABASE", "USERNAME"), password=env("DATABASE", "PASSWORD"), database=env("DATABASE", "DATABASE")) cursor = con.cursor() sql = "select * from table_name" res = cursor.execute(sql) print(res) cursor.close() con.close()

添加数据

# -*- coding: utf-8 -*- import pymysql from app.toolkit.env import * con = pymysql.connect(host=env("DATABASE", "HOSTNAME"), port=int(env("DATABASE", "HOSTPORT")), user=env("DATABASE", "USERNAME"), password=env("DATABASE", "PASSWORD"), database=env("DATABASE", "DATABASE")) cursor = con.cursor() try: sql = "insert into table_name (a,b) value (1,2)" res = cursor.execute(sql) con.commit() print(res) except Exception as e: print(e) cursor.close() con.close()

删除和修改与添加类似

注意:con.commit(),否则不生效

评论 1