pymysqleasy 是一款基于python开发的mysql 操作脚本,主要用于常用mysql 数据库的增删改查;脚本采用了单例模式,一次创建多次利用,并且有自动重连机制。断开链接后会重试连接。
仓库地址:https://github.com/duerhong/py-mysql-easy
安装
pip install pymysqleasy
连接数据库
from pymysqleasy import MysqlEasy
"""
Connect to the database
"""
conn = MysqlEasy(
host="127.0.0.1",
user="root",
password="root",
port=3306,
database="fanyi"
)
增删改查
def get_first_data():
ret = conn.first(
table_name="log",
condition={
"id": ["=", 1]
},
fields=['id', 'msg']
)
print(ret)
def get_multiple_data():
ret = conn.get(
table_name="log",
condition={
"id": [">", 1]
},
fields=['id', 'msg'],
start=0,
len=2
)
print(ret)
def get_all_data():
ret = conn.get(
table_name="log",
fields=['id', 'msg']
)
print(ret)
def get_total():
ret = conn.total(
table_name="log"
)
print(ret)
def insert_data():
"""
if return new data id,please use insertGetId
"""
ret = conn.insert(
table_name="log",
data={
"msg": "new data",
"user_id": 1
}
)
def update_data():
ret = conn.update(
table_name="log",
data={
"msg": "new data 111"
},
condition={
"id": ["=", 180]
}
)
def delete_data():
ret = conn.delete(
table_name="log",
condition={
"id": ["=", 180]
}
)
print(ret)
"""
other methods
exex(sql)
group_total(table_name, fields, condition)
"""
传递参数说明
condition: 构建where语句,格式如下
{
"field1": ['=', 'test1'],
'field2': ["=", 'test1']
}
order_by: 构建order by语句,格式如下
{
"id": "desc"
}
fields: select 选择字段
['id', 'field1']
data: 更新,新增 数据格式
{
"field1": "str1",
"field2": 1
}