python 连接 sqlite3 文件

 

# 0. pip install pymysql
# 1. 导入 pymysql  import pymsql
# 2. 创建一个数据库连接对象
# 3. 创建游标 cursor = conn.cursor()
# 4. SQL执行 cursor.execute(sql)
# 5. DML提交事务 conn.commit
# 6. 关闭游标 cursor.close()
# 7. 关闭连接 cursor.close()
import sqlite3

from Api_Test.utils.log_utils import logger

"""
sqlite是一种嵌入式数据库,它的数据库就是一个文件。
由于SQLite本身是用C写的,而且体积很小,所以经常被集成到各种应用程序中,甚至在IOS和Android的APP中都可以集成。
Python中内置了SQLite3,连接到数据库后,需要打开游标Cursor,通过Cursor执行SQL语句,然后获得执行结果,
Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可.
"""


class DataBase:

    def excute(self, sql):
        """
        获取mysql的连接
        :return: 返回一个数据库连接对象
        @return:
        """
        # 创建一个连接对象
        conn = sqlite3.connect("D:\\soft\\bysms\\resource\db.sqlite3")
        # 创建一个游标cursor
        cursor = conn.cursor()
        # 执行一条sql 语句

        try:
            logger.info(f'查询数据:{sql}')
            cursor.execute(sql)
        except BaseException as e:
            logger.error(f'查询失败{e.args}')
        else:
            logger.info('查询成功')
        # 获取结果集

        datas = cursor.fetchall()

        # 关闭 游标
        cursor.close()
        # 关闭 连接
        conn.close()
        return datas

# if __name__ == '__main__':
#     sql = 'select count(*) from common_customer'
#
#     result = DataBase().excute(sql)[0][0]
#
#     # print(DataBase().excute(sql))
#     print(result)

 

posted @ 2022-09-29 23:26  Avicii_2018  阅读(242)  评论(0)    收藏  举报