一般通过两种方式获取:1.for循环 2. 列表推导式。

比如我们目前有个一个txt文件,内容是superversion运行的任务。我们想把它写入数据库,就需要用executemany()方法来一次插入多行数据。要做到这一点,需要将文件中的数据先读取到一个列表中,然后对列表中的数据进行替换和切片,最后写入数据库。如下:

superversion.txt

superversion_list_server1  RUNNING 0:13:51
superversion_list_server2  RUNNING 0:13:52    
superversion_list_server3  RUNNING 0:13:53    
superversion_list_server4  RUNNING 0:13:54    
superversion_list_server5  RUNNING 0:13:55       
superversion_list_server6  RUNNING 0:13:56   
superversion_list_server7  RUNNING 0:13:57   
superversion_list_server8  RUNNING 0:13:58
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

insert_mysql.py

#coding:utf

import pymysql

# 数据库连接配置
config = {
    'user': 'root',
    'password': 'a1111',
    'host': '192.168.1.100',
    'database': 'shenji',
    'charset': 'utf8mb4',
    'port': 43306,
    'cursorclass': pymysql.cursors.DictCursor
}


connection = pymysql.connect(**config)  

try:
    with connection.cursor() as cursor: 
        with open('data.txt', 'r') as file:  # 打开txt文件并读取数据到列表中
            lines1 = file.readlines()  # 读取TXT文件中的数据,文件中的每行数据都是换行符隔开的,也就是一行一行的数据。readlines()是Python文件对象的一个方法,它用于读取文件中的所有行,并将它们作为一个字符串列表返回。
            print(type(lines1), lines1)

        lines2 = [i.strip().split(' ',2) for i in lines1]  
        # 为空值设定默认值
        for line in lines2:
            if len(line) < 3:  # 如果分割后的列表长度小于3,说明有空值
                line.extend(["DEFAULT"] * (3 - len(line)))  
            else:
                for i in range(len(line)):
                    if line[i] == '':  # 检查每个值是否为空
                        line[i] = "DEFAULT"  # 如果为空,则替换为默认值

        print(type(lines2), lines2)
        print("开始写入数据库")
        sql = "INSERT INTO saemonitor_saemonitor_superversior_kaihei1 (name,status,runtime) VALUES (%s, %s, %s)"  # 拼接SQL语句
        print(sql)
        cursor.executemany(sql,lines2)   # 批量插入数据;用executemany()方法来一次插入多行数据。要做到这一点,你需要将文件中的数据先读取到一个列表中,然后使用executemany()一次性插入所有数据。
        connection.commit()       # 提交事务
        print("数据已成功插入MySQL数据库!")

except Exception as e:
    # 如果上面代码发生异常,执行以下代码。
    print("发生错误:")
    print("发生错误%s: %e")
    # connection.rollback()   #发生异常时回滚事务

finally:
    #无论是否发生异常,最后都执行此代码,finally是异常处理结构的一部分,它通常与try和except一起使用
    connection.close()     # 关闭数据库连接
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.

运行结果:

~\Python38\python.exe  E:\python\从txt里读取内容往mysql写入数据\insert_mysql.py 
<class 'list'> ['overseas_sns_consumer RUNNING 0:13:56\n', 'overseas_sns_consumer RUNNING 0:13:56']
<class 'list'> [['overseas_sns_consumer', 'RUNNING', '0:13:56'], ['overseas_sns_consumer', 'RUNNING', '0:13:56']]
开始写入数据库
INSERT INTO saemonitor_saemonitor_superversior_kaihei1 (name,status,runtime) VALUES (%s, %s, %s)
数据已成功插入MySQL数据库!

进程已结束,退出代码0
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.