import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)try:with connection.cursor()as cursor:# Create a new record
sql ="INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql,('[email protected]','very-secret'))# connection is not autocommit by default. So you must commit to save your changes.
connection.commit()except Exception as e:print(e)# error rollback
connection.rollback()finally:
connection.close()
简单读操作
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)try:with connection.cursor()as cursor:# Read a single record
sql ="SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql,('[email protected]',))
result = cursor.fetchone()print(result)except Exception as e:print(e)finally:
connection.close()
#! /usr/bin/env python3# -*- coding:utf-8 -*-import pymysql
classPyMysql:
host ='localhost'
user ='user'
password ='pwssword'
db ='test'
charset ='utf8mb4'
cursorclass = pymysql.cursors.DictCursor
@classmethoddefquery(cls,sql,args=None,fetchone=False):# 创建连接
connection = pymysql.connect(host=cls.host, user=cls.user,
password=cls.password, db=cls.db, charset =cls.charset, cursorclass = cls.cursorclass)try:
result =None# 开启游标with connection.cursor()as cursor:# 返回响应结果数
effect_row = cursor.execute(cls.sql_args_2_sql(sql, args))if fetchone:
result = cursor.fetchone()else:
result = cursor.fetchall()except Exception as e:print(e)finally:# 关闭连接
connection.close()return result
@classmethoddefexecute(cls,sql,args=None,response=False):
connection = pymysql.connect(host=cls.host, user=cls.user,
password=cls.password, db=cls.db, charset =cls.charset, cursorclass = cls.cursorclass)try:
result =Nonewith connection.cursor()as cursor:
effect_row = cursor.execute(cls.sql_args_2_sql(sql, args))if response:
result = cursor.fetchall()# connection is not autocommit by default. So you must commit to save your changes.
connection.commit()except Exception as e:print(e)# error rollback
connection.rollback()finally:
connection.close()if response:return result
@staticmethoddefsql_args_2_sql(sql,args):'''
fix issue %d format: a number is required, not str
:param sql: sql语句
:param args: 格式化参数
:return: 组合之后的sql语句
'''if args isNone:return sql
if sql.find('%')>-1:return sql % args
elif sql.find('{')>-1:iftype(args)isdict:return sql.format(**args)else:return sql.format(*args)return sql
if __name__ =='__main__':#print(PyMysql.query(sql="select * from test where name = '%s' and age = %d ", args=('admin1', 18,), fetchone=True))#print(PyMysql.query(sql="select * from test where name = '{0}' and age = {1} ", args=('admin1', 18,),fetchone=True))#print(PyMysql.execute(sql="insert into test(name,gender,age) values('{name}','{gender}',{age})",args={'name':'admin6','gender':'女','age':18}))
dict_result = PyMysql.query(sql="select * from test where name = '{0}' ", args=('admin1',),fetchone=True)print(dict_result)print(dict_result['name'],dict_result['age'],dict_result['gender'])
PyMysql.execute(sql='UPDATE test set age = age +1 where id = %d ',args=(dict_result['id']))print(PyMysql.query(sql="select * from test where id = {0} ", args=(dict_result['id'],)))
PyMysql.cursorclass = PyMysql.cursors.Cursor
print(PyMysql.execute(sql="show tables",response=True))
%d format: a number is required, not str 错误解决
@staticmethoddefsql_args_2_sql(sql,args):'''
fix issue %d format: a number is required, not str
:param sql: sql语句
:param args: 格式化参数
:return: 组合之后的sql语句
'''if args isNone:return sql
if sql.find('%')>-1:return sql % args
elif sql.find('{')>-1:iftype(args)isdict:return sql.format(**args)else:return sql.format(*args)return sql