Python_day13--批量更新、数据库的封装、存储和读取照片、mysql远程备份

一、批量更新

前面我们产生了一些表单,username和passwd,当我们需要批量的修改时;

import pymysql
from colorFont import *

#连接数据库
conn = pymysql.connect(host='localhost',user='root',passwd='yutao',
                       db='yutao',charset='utf8')
#创建游标
cur = conn.cursor()
res = cur.execute('select * from userinfo;')
try:
    for i in range(20,31):
        print(i)
        update_sql = 'update userinfo set passwd="666666" where username="user%s";'
        cur.execute(update_sql, i)

except Exception as e :
    print(e)
    print(FAIL + "sql execute failed"+ END)
else:
    print(OKGREEN + "sql execute success" + END)

conn.commit()
cur.close()
conn.close()

代码内容很简单,我就不在此多作解释了,如果到你的电脑上跑不起来给你个建议,在你觉得可能会出错的地方打印,慢慢的就会排错;

二、封装数据库

在前面的几张博客中细心的你会发现,我们做了许许多多的重复,举个例子,就像下面的这些代码:

import pymysql
from colorFont import *

#连接数据库
conn = pymysql.connect(host='localhost',user='root',passwd='yutao',
                       db='yutao',charset='utf8')
#创建游标
cur = conn.cursor()
try:
    pass

except Exception as e :
    print(e)
    print(FAIL + "sql execute failed"+ END)
else:
    print(OKGREEN + "sql execute success" + END)

conn.commit()
cur.close()
conn.close()

那么我们为什么不想把法把他们打包封装起来,就像我们在使用标准库里的包一样,直接调用不是更好吗,下面我们就有了新的目标:把这些重复量很高的代码封装打包;

1、数据库信息封装

试想一下,你是一个数据库管理员,现在要你去上百台数据库中拿取东西,那么到要你记住每一个数据库的名字和信息吗?

为何不把他们封装在一起,你需要的时候可以轻易的调取就可以了;

注意:我们在起名子时,最好用英文数字,避免中文以免编码格式问题出现差错

db_config = {
    'host':'localhost',
    'user':'root',
    'passwd':'789',
    'db':'yutao',
    'charset':'utf8'
}

db_config01 = {
    'host':'localhost',
    'user':'root',
    'passwd':'456',
    'db':'yutao',
    'charset':'utf8'
}

db_config02 = {
    'host':'localhost',
    'user':'root',
    'passwd':'123',
    'db':'yutao',
    'charset':'utf8'
}

2、现在来封装连接数据库的函数类

这里的config包就是我们上面封装的数据库信息

import pymysql
import config
from colorFont import *

class Mypackage(object):
    def __init__(self,db_config):
        try:
            self.db_config = db_config
            self.conn = pymysql.connect(**self.db_config)
            self.cur = self.conn.cursor()
        except Exception as e:
            print(FAIL +'数据库连接失败:',e + END)

        else:
            print(OKGREEN +'数据库连接成功' + END)

    def __str__(self):
        return "Connect (%s user=%s db=%s)"%(self.db_config['host'],self.db_config['user'],self.db_config['db'])

    def __del__(self):
        self.conn.commit()
        self.cur.close()
        self.conn.close()

a = Mypackage(config.db_config)

以后如果我们需要,只需要改动很小的部分代码就能连接上数据库;

三、获取单个表的信息和字段

这部分代码其实是对前面mysql语句的应用而已,并没有特别难理解的内容
import  pymysql
from colorFont import *
# 1. 连接数据库连接
conn = pymysql.connect(host='localhost', user='root',
                       passwd='yutao', db='yutao',
                       charset='utf8')

# 2. 创建游标, 给数据库发送sql指令
cur = conn.cursor()
try:
    # 3. 执行sql语句: 查看数据
    res = cur.execute('select * from userinfo;')
    desc = cur.description
    print("表的描述信息:", desc)

    table_header = [item[0] for item in desc]
    print("表头:", table_header)
    
    print("\t".join(table_header))
    for row in cur.fetchall():
        print("\t".join(row))
except Exception as e:
    print(e)
    print(FAIL + "sql execute failed" + END)
else:
    print(OKGREEN + "sql execute success" + END)


# 4. 先关闭游标
cur.close()
# 5. 关闭数据库连接
conn.close()

四、给我们的数据库中插入图片

首先还是建立连接、创建邮标;

import pymysql
from colorFont import *

conn = pymysql.connect(host='localhost', user='root',
                       passwd='yutao', db='westos',
                       charset='utf8')

# 2. 创建游标, 给数据库发送sql指令
cur = conn.cursor()

# 3. 执行sql语句:

# 1). 创建存储图片的数据库表;
try:
    cur.execute('create table images(id int primary key auto_increment , imgName varchar(50),imgData mediumblob); ')
except Exception as e:
    print(e)
    print(FAIL + "sql execute failed" + END)
else:
    print(OKGREEN + "table create sucess!" + END)

# 2). 插入图片;
try:

    insert_sqli = 'insert into images (imgName, imgData) values(%s, %s);'
    f = open('img/img01.jpg', 'rb')
    img_data = f.read()
    f.close()
    cur.execute(insert_sqli, ('img01.jpg', img_data ))
except Exception as e:
    print(e)
else:
    print("插入图片信息成功!")

conn.commit()
# 4. 先关闭游标
cur.close()
# 5. 关闭数据库连接
conn.close()

我们在创建储存图片的数据库时,可以现在我们的命令行实现,然后再粘到我们的语句中,避免了手残敲错字母导致没法成功;

我们写入数据库的是以二进制的方式写入的,所以文件打开方式为‘rb’


我们这里的照片放在了当前统一目录下,所以时用的是相对路径;如果你的照片放在其他目录中,那么就要用绝对路径;可是当我们查看images时,看到一堆乱码,可是这并不是我们希望看到的结果

所以,请往下看...

五、读取照片

这里我们进行了强转码,把二进制强转为utf8

import json

import pymysql
from colorFont import *

conn = pymysql.connect(host='localhost', user='root',
                       passwd='yutao', db='westos',
                       charset='utf8')

# 2. 创建游标, 给数据库发送sql指令
cur = conn.cursor()
try:
    cur.execute("select * from images")
    with open('image.png', 'wb') as fout:
        fout.write((json.dumps(cur.fetchone()[0]).encode('utf8')))
        # fout.write(cur.fetchone()[0])



except Exception as e:
    print(e)
    print(FAIL + "sql execute failed" + END)
else:
    print(OKGREEN + "sql execute success" + END)

cur.close()
conn.close()

六、多台mysql主机的远程备份

import os

from colorFont import *

import time
mysql_list = [
    {
        'host':'172.25.254.60',
        'user':'root',
        'passwd':'yutao',
        'db':'yutao'
    }
    ]

BACKUP_DIR = '/tmp/BACKUP/'

if not os.path.exists(BACKUP_DIR):
    os.mkdir(BACKUP_DIR)
    print("%s create success!" % (BACKUP_DIR))
else:
    try:
        for host in mysql_list:
            # date = os.popen('date +%Y_%m_%d')
            shell_sen = "mysqldump -h %s -u%s -p%s %s >%s"
            host_ip = host['host']
            user = host['user']
            passwd = host['passwd']
            db = host['db']
            backup_filename = BACKUP_DIR + '%s_%s.dump' %(host_ip, db)
            print(backup_filename)
            print(shell_sen % (host_ip, user, passwd, db, backup_filename))
            os.system(shell_sen % (host_ip, user, passwd, db, backup_filename))
            print("backup %s host" %(host_ip))
    except Exception as e:
        print(e)
        print(FAIL + "sql execute failed" + END)
    else:
        print(OKGREEN + "sql execute success" + END)
os.mknod(time.ctime())









猜你喜欢

转载自blog.csdn.net/Biu_Biu_0329/article/details/80609302
今日推荐