#coding=utf-8 import MySQLdb db = MySQLdb.connect("IP","用户名","密码","库名",charset = 'utf8') cursor = db.cursor() f = open("文件名.txt", "r") i = 1000000001 for eachline in f: sql = "INSERT INTO 表名(id, quanwen) VALUES (%d, \'%s\')" % (i, eachline) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() i += 1 except: # Rollback in case there is any error db.rollback() # 关闭数据库连接 db.close() f.close()
本文介绍了一种使用Python批量将文本文件中的数据插入MySQL数据库的方法。通过读取文件中的每一行内容并构造SQL插入语句来实现这一过程。同时,该文提供了错误处理机制确保数据正确入库。
866

被折叠的 条评论
为什么被折叠?



