简体   繁体   English

Python - 使用MySQLDB从For循环插入记录

[英]Python — Inserting Record from For Loop using MySQLDB

I have done the tutorials but I am far from an accomplished python hacker. 我已经完成了教程,但我远非一个成功的python黑客。

I am trying to do the following using MySQLdb: 我试图使用MySQLdb执行以下操作:

  1. loop through a list of files from a directory 循环遍历目录中的文件列表
  2. generate a new file name for these files based on function parameters 根据函数参数为这些文件生成新文件名
  3. insert a database record with the new filename 使用新文件名插入数据库记录
  4. move the file to the new directory using the new filename. 使用新文件名将文件移动到新目录。

I have items 1,2 and 4 working but can't get the database insert working correctly. 我有项目1,2和4工作,但无法使数据库插入正常工作。 There is not an error but nothing is inserted into the table. 没有错误,但表中没有插入任何内容。 I can login and access the database through a command prompt, and I can insert a record into the table directly. 我可以通过命令提示符登录并访问数据库,我可以直接在表中插入记录。

I am using python 2.75, mySQL 5.6.13, windows 7 64bit, and MySQL_python-1.2.4-py2.7-win32 installed using easy_install. 我正在使用easy_install安装python 2.75,mySQL 5.6.13,windows 7 64bit和MySQL_python-1.2.4-py2.7-win32。

def moveFile(rPath, dPath, dbID):
import fnmatch
import os
import MySQLdb as mysql
import sys
conn = mysql.connect(host='localhost', user='*******', passwd='*******', db='*******')
pattern = '*.pdf'
inc = 0
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        dire = root.find(rootPath) + len(rootPath)
        dest = destPath + root[dire:]
        fname = dbID + "_" + str(inc) + ".pdf"
        # print fname
        # print os.path.join(root, filename),  os.path.join(dest, fname)
        # os.renames(os.path.join(root, filename), os.path.join(dest, fname))
        x = conn.cursor()
        x.execute("INSERT INTO documents(documentname) VALUES (fname)")
        inc += 1

return 'Files Count: ', inc

I am sure I need to commit somewhere in the code but my attempts have produced no error but also no results. 我确信我需要在代码中的某处提交,但我的尝试没有产生错误但也没有结果。

Thanks for reading my question land I will try all suggestions promptly. 感谢您阅读我的问题土地,我会及时尝试所有建议。

Replace x.execute(...) line as follow: 替换x.execute(...)行如下:

    x.execute("INSERT INTO documents(documentname) VALUES (%s)", (fname,))

And commit at the end. 最后提交。

conn.commit()

Yes, definitely unless you commit the transaction you won't see any results in the DB. 是的,绝对除非你提交交易,否则你不会在数据库中看到任何结果。 Do this after you've executed all the inserts. 执行完所有插入后执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM