zoukankan      html  css  js  c++  java
  • 【程序员技术练级】学习一门脚本语言 python(三)跟数据库打交道

    接着上一篇,该篇讲述使用python对数据库进行基本的CRUD操作,这边以sqlite3为例子,进行说明。sqlite3 是一个非常轻型的数据库,安装和使用它是非常简单的,这边就不进行讲述了。

    在python下,已经自带了sqlite3模块,供我们使用,这个模块的用途其实和JAVA当中的jdbc驱动是类似的,通过它,我们就可以非常方便的和sqlite3进行各种操作了。

    好了,开始吧。

    python的数据库模块有统一的接口标准,所有的操作都有统一的模式,大概是分为以下几步(假设使用的是sqlite3模块):

    1. 用sqlite3.connect()获取数据库的连接,假设连接为conn
    2. 如果我们的操作不需要返回结果,那么就可以直接执行conn.execute(sql)。
    3. 由于数据库事务隔离级别的不同,如果我们执行的是对数据库的修改或者插入,那么我们需要执行conn.commit()
    4. 如果需要返回结果,那么conn.cursor()创建游标对象cursor,通过cursor.execute查询数据库,用cursor.fetchall/cur.fetchone/cur.fetchmany返回查询结果。
    5. 由于数据库事务隔离级别的不同,如果我们执行的是对数据库的修改或者插入,那么我们需要执行cur.commit()
    6. 最后,最重要的是 对conn和cursor进行关闭,cursor.close()、conn.close() (先关闭cursor,在关闭conn)

    具体的相关CRUD实现代码如下:

    import os
    import sqlite3
    
    #根据传入的path获取一个数据库连接,如果path非法,那么创建一个临时的内存数据库
    def get_conn(path):
    
        conn = sqlite3.connect(path)
    
        if os.path.exists(path) and os.path.isfile(path):
            print('database path is %s' % format(path))
            return conn
        else:
            conn = None
            return sqlite3.connect(':memory')
    #获取游标
    def get_cursor(conn):
        if conn is not None:
            return conn.cursor()
        else:
            return get_conn('').cursor()
    #创建表数据
    def create_table(conn, sql):
        if sql is not None and sql != '':
            cursor = get_cursor(conn)
            cursor.execute(sql)
            conn.commit()
            close_all(conn, cursor)
    
    #关闭数据库连接
    def close_all(conn, cursor):
        try:
            if cursor is not None:
                cursor.close()
        finally:
            if conn is not None:
                conn.close()
    #CURD操作,需要返回值,查询是肯定有返回值
    def crud(conn, sql, data):
        cursor = get_cursor(conn)
        n = cursor.execute(sql, data)
        print("n", n.rowcount)
        fetchall = cursor.fetchall()
        conn.commit()
        close_all(conn, cursor)
        return fetchall
    #CRUD操作,不需要返回值,查询是肯定有返回值
    def crud(conn, sql, data):
        cursor = get_cursor(conn)
        n = cursor.execute(sql, data)
        conn.commit()
        close_all(conn, cursor)

    一个简单的例子:

    conn = get_conn('D:/temp/sqlite3/test.db')
    fetchall = crud(conn, 'select * from student', '')
    
    #假设返回的数据有三个字段
    for row in fetchall:
        print('name: %s, age: %d, address: %s' % (row[0], row[1], row[2]))

    好了,上面的代码就是最简单的对python的数据库操作了。

    大家如果有什么问题或者文件有什么错误的话,可以留言大家一起探讨!

  • 相关阅读:
    Linux 安装nginx
    Linux服务器svn与项目同步
    Linux服务器安装svn
    Thinkphp5模板继承
    Thinkphp5 Route用法
    一键切换hosts文件
    lnmp手动新建虚拟机
    wamp 配置虚拟主机
    百度编辑器
    百度编辑器:上传图片二
  • 原文地址:https://www.cnblogs.com/vhua/p/python_3.html
Copyright © 2011-2022 走看看