python学习笔记12(python连接数据库)

python连接数据库

安装第三方软件来建立python和数据库的连接
-python2-------》MySQL-python.x86_64
yum install MySQL-python.x86_64
-python3-------》pymysql
用pip下载,yum源中没有该软件包
pip install pymysql
  • 创建数据表
import pymysql

# 1. 连接数据库,
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='redhat',
    db='helloTest',
    charset='utf8',
    autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = conn.cursor()
# 3.
try:
    create_sqli = "create table hello (id int, name varchar(30));"
    cur.execute(create_sqli)
except Exception as e:
    print("创建数据表失败:", e)
else:
    print("创建数据表成功;")


# 4. 关闭游标
cur.close()
# 5. 关闭连接
conn.close()

在这里插入图片描述
在这里插入图片描述

  • 插入数据
import pymysql

# 1. 连接数据库,
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='redhat',
    db='helloTest',
    charset='utf8',
    autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = conn.cursor()
# 3.
try:
    insert_sqli = "insert into hello values(2, 'fensi');"
    cur.execute(insert_sqli)
except Exception as e:
    print("插入数据失败:", e)
else:
    # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
    conn.commit()
    print("插入数据成功;")
# 4. 关闭游标
cur.close()
# 5. 关闭连接
conn.close()

在这里插入图片描述
在这里插入图片描述

  • 插入多条数据
import pymysql

# 1. 连接数据库,
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='redhat',
    db='helloTest',
    charset='utf8',
    autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = conn.cursor()
# 3.
try:
    info = [(i, "westos%s" %(i)) for i in range(100)]

    # *********************第一种方式********************
    # # %s必须手动添加一个字符串, 否则就是一个变量名, 会报错.
    # insert_sqli = "insert into hello values(%d, '%s');"
    # for item in info:
    #     print('insert语句:', insert_sqli %item)
    #     cur.execute(insert_sqli %item)

    # *********************第二种方式********************
    insert_sqli = "insert into hello values(%s, %s);"
    cur.executemany(insert_sqli, info )
except Exception as e:
    print("插入多条数据失败:", e)
else:
    # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
    conn.commit()
    print("插入多条数据成功;")
# 4. 关闭游标
cur.close()
# 5. 关闭连接
conn.close()

在这里插入图片描述
在这里插入图片描述

  • 数据库查询
import pymysql

# 1. 连接数据库,
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='redhat',
    db='helloTest',
    charset='utf8',
    autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = conn.cursor()
# 3.
sqli = "select * from hello;"
result = cur.execute(sqli)  # 默认不返回查询结果集, 返回数据记录数。
print(result)

print(cur.fetchone())     # 1). 获取下一个查询结果集;
print(cur.fetchone())
print(cur.fetchone())

print(cur.fetchmany(4))   # 2). 获取制定个数个查询结果集;

info = cur.fetchall()     # 3). 获取所有的查询结果
print(info)
print(len(info))

print(cur.rowcount)       # 4). 返回执行sql语句影响的行数
# 4. 关闭游标
cur.close()
# 5. 关闭连接
conn.close()

在这里插入图片描述

获取表的字段名和信息

import pymysql

# 1. 连接数据库,
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='redhat',
    db='helloTest',
    charset='utf8',
    # autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.



# __enter__, __exit__

# with语句实现的效果是: with语句执行结束, 如果成功, 则提交改变的数据, 如果不成功, 则回滚.
with conn:
    # ****** 判断是否连接?
    print(conn.open)  # True
    # 2. 创建游标对象,
    cur = conn.cursor()
    # 3).
    sqli = "select * from hello;"
    result = cur.execute(sqli)  # 默认不返回查询结果集, 返回数据记录数。

    # 显示每列的详细信息
    des = cur.description
    print("表的描述:", des)

    # 获取表头
    print("表头:", ",".join([item[0] for item in des]))
    cur.close()


conn.close()
print("with语句之外:", conn.open)   # False

在这里插入图片描述

基于mysql数据库银行转账功能实现

import pymysql


class TransferMoney(object):
    # 构造方法
    def __init__(self, conn):
        self.conn = conn
        self.cur = conn.cursor()

    def transfer(self, source_id, target_id, money):
        # 1). 判断两个银行卡号是否存在?
        # 2). 判断source_id是否有足够的钱?
        # 3). source_id扣钱
        # 4). target_id加钱
        if not self.check_account_avaialbe(source_id):
            raise  Exception("账户不存在")
        if not self.check_account_avaialbe(target_id):
            raise  Exception("账户不存在")

        if self.has_enough_money(source_id, money):
            try:
                self.reduce_money(source_id, money)
                self.add_money(target_id, money)
            except Exception as e:
                print("转账失败:", e)
                self.conn.rollback()
            else:
                self.conn.commit()
                print("%s给%s转账%s金额成功" % (source_id, target_id, money))

    def check_account_avaialbe(self, acc_id):
        """判断帐号是否存在, 传递的参数是银行卡号的id"""
        select_sqli = "select * from bankData where id=%d;" % (acc_id)
        print("execute sql:", select_sqli)
        res_count = self.cur.execute(select_sqli)
        if res_count == 1:
            return True
        else:
            # raise  Exception("账户%s不存在" %(acc_id))
            return False

    def has_enough_money(self, acc_id, money):
        """判断acc_id账户上金额> money"""
        # 查找acc_id存储金额?
        select_sqli = "select money from bankData where id=%d;" % (acc_id)
        print("execute sql:", select_sqli)
        self.cur.execute(select_sqli)  # ((1, 500), )

        # 获取查询到的金额钱数;
        acc_money = self.cur.fetchone()[0]
        # 判断
        if acc_money >= money:
            return True
        else:
            return False

    def add_money(self, acc_id, money):
        update_sqli = "update bankData set money=money+%d  where id=%d" % (money, acc_id)
        print("add money:", update_sqli)
        self.cur.execute(update_sqli)

    def reduce_money(self, acc_id, money):
        update_sqli = "update bankData set money=money-%d  where id=%d" % (money, acc_id)
        print("reduce money:", update_sqli)
        self.cur.execute(update_sqli)

    # 析构方法
    def __del__(self):
        self.cur.close()
        self.conn.close()


if __name__ == '__main__':
    # 1. 连接数据库,
    conn = pymysql.connect(
        host='localhost',
        user='root',
        password='redhat',
        db='helloTest',
        charset='utf8',
        autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
    )
    trans = TransferMoney(conn)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mkgdjing/article/details/86759551