Python 边做边学 8.3 工具类--数据库工具(DbUtil)

原文连接:http://blog.csdn.net/tomorrow13210073213/article/category/6931287

数据持久化

采集到的数据需要保存起来,这是个demo项目,选用什么方式做数据持久化并不是十分重要,重要的是把数据存起来;

之前项目一直在用mysql,所以此处也使用mysql做数据存储;

搜索“python3 操作mysql”

搜索“python3 操作mysql”,找到一篇比较靠谱的:

http://blog.csdn.net/nuli888/article/details/51960571

文章开头“python3.x 使用pymysql操作MySQL,python2.x使用mysqldb操作mysql”告诉我们“python3.x 使用pymysql操作MySQL”;用pycharm下载“pymysql”包之后,就可以使用了;

“pymysql”操作数据库与其他编程语言类似:
建立连接
获取游标
执行语句
提交结果
关闭游标
关闭链接

DbUtil.py代码
import pymysql

from lufaxin.csdn.util import CfgUtil

__host = CfgUtil.get_db("host")
__user = CfgUtil.get_db("user")
__passwd = CfgUtil.get_db("passwd")
__db = CfgUtil.get_db("db")
__port = int(CfgUtil.get_db("port"))
__charset = CfgUtil.get_db("charset")


def execute(sql_str):
    if sql_str is None:
        raise Exception("参数不能为空:sql_str")
    if len(sql_str) == 0:
        raise Exception("参数不能为空:sql_str")
    try:
        conn = pymysql.connect(host=__host, user=__user, passwd=__passwd, db=__db,
                               port=__port, charset=__charset)
        cur = conn.cursor()  # 获取一个游标
        cur.execute(sql_str)
        data = cur.fetchall()
        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 释放数据库资源
        return data
    except Exception as e:
        raise e


# 插入数据,返回数据主键
def execute_insert(insert_str, data):
    if insert_str is None:
        raise Exception("参数不能为空:sql_str")
    if len(insert_str) == 0:
        raise Exception("参数不能为空:sql_str")
    try:
        conn = pymysql.connect(host=__host, user=__user, passwd=__passwd, db=__db,
                               port=__port, charset=__charset)
        cur = conn.cursor()  # 获取一个游标
        cur.execute(insert_str, data)
        data = cur.fetchall()
        # last_id = cur.lastrowid
        last_id = conn.insert_id()
        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 释放数据库资源
        return last_id
    except Exception as e:
        raise e


# 更新数据,返回更新条数
def execute_update(update_str, data):
    if update_str is None:
        raise Exception("参数不能为空:update_str")
    if len(update_str) == 0:
        raise Exception("参数不能为空:update_str")
    try:
        conn = pymysql.connect(host=__host, user=__user, passwd=__passwd, db=__db,
                               port=__port, charset=__charset)
        cur = conn.cursor()  # 获取一个游标
        count = cur.execute(update_str, data)
        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 释放数据库资源
        return count
    except Exception as e:
        raise e


# 执行带参数的查询,返回查询结果
def execute_select(select_str, data):
    if select_str is None:
        raise Exception("参数不能为空:sql_str")
    if len(select_str) == 0:
        raise Exception("参数不能为空:sql_str")
    try:
        conn = pymysql.connect(host=__host, user=__user, passwd=__passwd, db=__db,
                               port=__port, charset=__charset)
        cur = conn.cursor()  # 获取一个游标
        cur.execute(select_str, data)
        data = cur.fetchall()
        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 释放数据库资源
        return data
    except Exception as e:
        raise e


# 执行带参数的删除
def execute_delete(select_str, data):
    if select_str is None:
        raise Exception("参数不能为空:sql_str")
    if len(select_str) == 0:
        raise Exception("参数不能为空:sql_str")
    try:
        conn = pymysql.connect(host=__host, user=__user, passwd=__passwd, db=__db,
                               port=__port, charset=__charset)
        cur = conn.cursor()  # 获取一个游标
        cur.execute(select_str, data)
        data = cur.fetchall()
        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 释放数据库资源
        return data
    except Exception as e:
        raise e
数据库链接

数据库连接信息来自配置文件:

__host = CfgUtil.get_db("host")
__user = CfgUtil.get_db("user")
__passwd = CfgUtil.get_db("passwd")
__db = CfgUtil.get_db("db")
__port = int(CfgUtil.get_db("port"))
__charset = CfgUtil.get_db("charset")
创建连接

通过“pymysql.connect()”方法创建数据库连接:

conn = pymysql.connect(host=__host, user=__user, passwd=__passwd, db=__db, port=__port, charset=__charset)
获取游标
cur = conn.cursor()  # 获取一个游标
执行语句
cur.execute(sql_str)
data = cur.fetchall()
提交结果
conn.commit()
关闭连接,游标
cur.close()  # 关闭游标
conn.close()  # 释放数据库资源
参数传递

如上面定义的“execute”方法所示,可以只传递一个参数,那就是要执行的sql语句;这种方式执行简单操作可以,但执行复杂插入,更新等操作会比较复杂;所以有了下面几个方法,用来执行不同的操作(增删改查),不再一一介绍;

调用方法
from lufaxin.csdn.util import DbUtil

......

sql = "select " + cols_str + " from " + table_name + " where " + t_pk + " = " + str(pk)
sel_data = DbUtil.execute(sql)

......

sql = "delete from " + table_name + " where " + pk_name + " = " + str(pk)
del_data = DbUtil.execute(sql)

其他方法类似,构建各表数据库操作基础类的的时候,再详细描述各方法的用法;

以上就是我们用到的数据库操作工具类;

以上内容仅供练习,学习使用;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值