python-数据库(mariadb)

01_数据库基本数语

数据库 database
数据表 table
主键 primary key
表头

02_mysql数据类型之数值

在这里插入图片描述

03_mysql数据类型之日期在这里插入图片描述

04_mysql数据类型之字符串在这里插入图片描述

05_数据库之属性设置在这里插入图片描述

06_mariadb

1. 安装mysql

yum search mariadb
//查找与mariadb有关的软件包

yum install mariadb mariadb-server -y
//安装mariadb的server软件和client软件

  1. 启动mariadb服务
    systemctl start mariadb
    systemctl enable mariadb

  2. mariadb监听的端口
    netstat -antlpe | grep mysql
    ss -antlpe | grep mysql
    vim /etc/services //所有服务与端口默认的对应关系

  3. 只允许本地连接,阻断所有来自网络的连接
    vim /etc/my.cnf
    skip-networking=1
    systemctl restart mariadb

2. mariadb的初始化

1)设置mysql的登陆密码

mysql_secure_installation
mysql -uroot -p

2)mysql基本操作语句
show databases;                          //显示数据库,类似于目录,里面包含多个表
use mysql;                               //进入名称为mysql的数据库
show tables;                             //显示该数据库中的表
desc user;                               //显示表的结构
select * from user;                      //显示user表中的内容
select Host,User,Password from user;     //显示表中某几列
create database westos;                  //创建以数据库名称为westos
create table westosuser(                 //创建一表
  -> username varchar(10) not null,
  -> passwd varchar(6) not null
  -> );

insert into westosuser values ('user1','123');                   //向表中插入内容
insert into westosuser(passwd,username) values("456","user2");   //按照指定顺序向表中插入数据
update westosuser set passwd='456' where username="user1";       //更新表中的内容

alter table westosuser add sex varchar(3);                       //添加sex列到westosuser表中
delete from westosuser where username="user1";                   //删除表中用户名为user1的记录
drop table westosuser;                                           //删除表
drop database westos;                                            //删除数据库

3.用户和访问权限的操作

create user hello@localhost identified by 'hello';
//创建用户hello,可在本机登陆,密码为hello

create user hello@'%' identified by 'hello';
//创建用户hello,可在远程登陆,密码为hello

create database mariadb;
//创建一数据库mariadb,对普通用户进行

grant all on mariadb.* to hello@localhost;
//给hello@localhost用户授权,如果为all,授权所有权限
(insert,update,delete,select,create)

flush privileges;                                            //刷新,重载授权表
show grants for hello@localhost;                             //查看用户授权
revoke delete,update on mariadb.* from hello@localhost;      //删除指定用户授权
drop user hello@localhost;                                   //删除用户

4. 忘记mysql用户密码时,怎么找回?

  1. 关闭mariadb服务
    systemctl stop mariadb
  2. 跳过授权表
    mysqld_safe --skip-grant-table &
  3. 修改root密码
    mysql
    update mysql.user set Password=password(‘westos’) where User=‘root’;
  4. 关闭跳过授权表的进程,启动mariadb服务,使用新密码即可
    ps aux | grep mysql
    kill -9 pid
    mysql -uroot -p

5. mysql的备份与恢复

备份:
mysqldump -uroot -p mariadb >mariadb.dump
mysqldump -uroot -pwestos --no-data mariadb > date +%Y_%m_% d_mariadb.dump
mysqldump -uroot -pwestos --all-databases >mariadb4.dump

恢复:
mysqladmin -uroot -pwestos create mariadb2
mysql -uroot -pwestos mariadb2< mariadb.dump

07_python连接数据库

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. 对于数据库进行增删改查
# 1). ************************创建数据表**********************************
try:
    create_sqli = "create table hello (id int, name varchar(30));"
    cur.execute(create_sqli)
except Exception as e:
    print("创建数据表失败:", e)
else:
    print("创建数据表成功;")


# 2). *********************插入数据****************************
try:
    insert_sqli = "insert into hello values(2, 'fensi');"
    cur.execute(insert_sqli)
except Exception as e:
    print("插入数据失败:", e)
else:
    # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
    conn.commit()
    print("插入数据成功;")


# 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). **************************数据库查询*****************************
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语句影响的行数

#  5). 移动游标指针
print(cur.fetchmany(3))
print("正在移动指针到最开始......")
cur.scroll(0, 'absolute')
print(cur.fetchmany(3))

print("正在移动指针到倒数第2个......")
print(cur.fetchall())    # 移动到最后
cur.scroll(-2, mode='relative')
print(cur.fetchall())

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

08_获取表的字段名和信息

import time

import pymysql

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

# __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

09_基于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)
    # assert trans.check_account_avaialbe(14255632) == False
    # assert  trans.check_account_avaialbe(13997) == True
    #
    #
    # assert  trans.has_enough_money(13997, 800) == False
    # assert  trans.has_enough_money(13998, 700) == True
    # trans.add_money(13998, 200)
    # trans.reduce_money(13998, 200)
    # # trans.transfer(12567, 16787, 100)
    # trans.transfer(13997, 13998, 200)
```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)
    # assert trans.check_account_avaialbe(14255632) == False
    # assert  trans.check_account_avaialbe(13997) == True
    #
    #
    # assert  trans.has_enough_money(13997, 800) == False
    # assert  trans.has_enough_money(13998, 700) == True
    # trans.add_money(13998, 200)
    # trans.reduce_money(13998, 200)
    # # trans.transfer(12567, 16787, 100)
    # trans.transfer(13997, 13998, 200)

猜你喜欢

转载自blog.csdn.net/qq_43273590/article/details/86525239
今日推荐