my_sql.py 内容如下:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pymysql
import os
from common.MyConf import MyConf
from common.my_path import Conf_dir
class MySql:
def __init__(self):
# 实例化配置类对象
conf = MyConf(os.path.join(Conf_dir, 'mysql.ini'))
# 1.数据库连接、生成游标
self.db = pymysql.connect(
host=conf.get("mysql", "host"),
user=conf.get("mysql", "user"),
password=conf.get("mysql", "passwd"),
port=conf.getint("mysql", "port"),
database=conf.get("mysql", "database"),
charset="utf8",
cursorclass=pymysql.cursors.DictCursor
)
#2.创建游标
self.cur = self.db.cursor()
#获取查询条数
def get_count(self,sql):
count = self.cur.execute(sql)
return count
#获取查询的第一条数据
def get_one_data(self,sql):
self.cur.execute(sql)
return self.cur.fetchone()
#获取查询的多条数据
def get_many_data(self,sql,size=None):
self.cur.execute(sql)
if size:
return self.cur.fetchmany(size)
else:
return self.cur.fetchall()
#先关闭游标连接,再关闭数据库连接
def close_db(self):
self.cur.close()
self.db.close()
if __name__ == '__main__':
my_db = MySql()
sql = "select id from order where order_id='1335****'"
count = my_db.get_count(sql)
print(count)
my_db.close_db()
另外补充下MyConf.py , my_sql.ini 内容:
MyConf.py 如下
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from configparser import ConfigParser
class MyConf(ConfigParser):
def __init__(self,filename):
super().__init__()
self.read(filename,encoding='utf-8')
my_sql.ini 格式如下(*表示需要替换成项目对应数据库信息)
[mysql]
host=***
database=**
port=***
user=**
passwd=***