python脚本

时间:2020-04-07 10:01:46   收藏:0   阅读:68

数据库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)

原文:https://www.cnblogs.com/sihye/p/12636859.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!