python連線mysql並插入資料(自用)

右介發表於2017-06-06

 

#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()

 

相關文章