zoukankan      html  css  js  c++  java
  • python脚本

    数据库mysql连接练习

    查询某个目录下的所有文件内容中的sql语句,并执行到数据库中。

    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    
    # 导入库
    from pathlib import Path
    import pymysql
    
    try:
        # 数据库连接方式定义,并调用cursor方法连接
        db = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456@Hsh')
        conn = db.cursor()
        # 定义目录位置
        file_base = Path(r'/server/tmp/files')
        # 定义一个空列表
        lineu = []
        # 用rglob方法来获取目录下所有文件的绝对路径
        for p in file_base.rglob('*'):
          # 用open方法打开文件,r模式表示读
          with open(str(p), encoding='utf-8', mode='r') as f:
            # 将读取到的行赋给sql_list
            sql_list = f.read()
            # 将行插入空列表
            lineu.append(sql_list)
            # 遍历新列表
            for i in lineu:
              try:
                # i为获取到的每行sql语句,用excute方法执行
                conn.execute(i)
                # 执行后输出结果
                print('%s is done!' % (i))
                # 执行完成后在新列表中删除该语句,防止多次读取
                lineu.remove(i)
              # 若sql执行失败
              except Exception as e:
                print(e)
                print('%s is faield!' % (i))
                lineu.remove(i)
    finally:
      # 全部任务完成后关闭连接,提交所有事务,关闭数据库
        conn.close()
        db.commit()
        db.close()
    

    RUN:

    mysql> select * from noc.halo;
    +------+------+
    | code | name |
    +------+------+
    | 1    | 2    |
    | 10   | 11   |
    | 2    | 3    |
    | 3    | 4    |
    | 4    | 5    |
    | 5    | 6    |
    | 6    | 7    |
    | 7    | 8    |
    | 8    | 9    |
    | 9    | 10   |
    +------+------+
    10 rows in set (0.00 sec)
    

    通过函数的形式

    
    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    # -------------------------------------------------
    # author: sihye
    # date: 2020-3-5
    # order: scripts using by python and mysql practice
    # -------------------------------------------------
    # 导入库
    from pathlib import Path
    import pymysql
    
    '''
    get_files函数:遍历目录下的所有文件,并读取内容
    函数:获取给定目录下的所有文件的绝对路径
    参数path: 定义文件目录
    参数pattern:定义返回的文件类型,默认返回所有文件,可自定义返回类型,如pattern='*.py'
    以';'来分割读取文本,获取值插入新列表
    列表all_file:定义一个空列表来存放获取到的sql语句
    '''
    def get_files(path, pattern='*'):
        all_file = []
        files = Path(path).rglob(pattern)
        for file in files:
            with open(str(file), encoding='utf-8', mode='r') as f:
                sql = f.read().split(';')
                all_file.append(sql)
        return all_file
    '''
    con_db函数:连接数据库
    pymysql_connect方法打开数据库连接
    调用cursor方法来创建一个游标对象cursor
    
    

    将遍历获取到得值插入新得空列表

    # 定义一个空列表,然后去遍历获取列表每个元素
    one = [1, 2, 3, 4, 5]
    # 每次循环都会清空一次列表,输出时就只有循环到得单个元素
    for p in one:
    	two = []
    	two.append(p)
    	print(two)
    #运行结果
    #[1]
    #[2]
    #[3]
    #[4]
    #[5]
    
    # 定义一个空列表,然后去遍历获取列表每个元素
    one = [1, 2, 3, 4, 5]
    two = []
    # 每次循环都会向空列表中添加一次遍历到得值,每次遍历都从从第一个开始
    for p in one:
    	two.append(p)
    	print(two)
    
    #运行结果
    # [1]
    # [1, 2]
    # [1, 2, 3]
    # [1, 2, 3, 4]
    # [1, 2, 3, 4, 5]
    
  • 相关阅读:
    求约数的个数-牛客
    成绩排序 -- 牛客
    SpringBoot学习笔记4-整合Jdbc Template-Mybatis-多数据源-事务管理-JPA
    SpringBoot学习笔记3-自定义拦截器-全局异常处理-Freemarker-Thymeleaf-定时任务调度
    SpringBoot学习笔记2-日志管理-开发模式-web开发-FastJson
    SpringBoot学习笔记1-简介-全局配置文件-starter-profiles-自动配置原理
    将Ueditor文件上传至OSS
    nouveau :failed to create kernel chanel,-22
    教你怎么炼鸡肉
    教你怎么写猜年龄游戏
  • 原文地址:https://www.cnblogs.com/sihye/p/12636859.html
Copyright © 2011-2022 走看看