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

时间:2013-08-04 14:56:30

标签: python mysql-python

我已经完成了教程,但我远非一个成熟的python黑客。

我正在尝试使用MySQLdb执行以下操作:

  1. 遍历目录中的文件列表
  2. 根据函数参数
  3. 为这些文件生成新文件名
  4. 使用新文件名
  5. 插入数据库记录
  6. 使用新文件名将文件移动到新目录。
  7. 我有1,2和4项工作,但无法使数据库插入正常工作。没有错误,但表中没有插入任何内容。我可以通过命令提示符登录并访问数据库,我可以直接在表中插入记录。

    我正在使用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
    

    我确信我需要在代码中的某处提交,但我的尝试没有产生错误但也没有结果。

    感谢您阅读我的问题,我将及时尝试所有建议。

2 个答案:

答案 0 :(得分:1)

x.execute(...)行替换为:

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

最后提交。

conn.commit()

答案 1 :(得分:1)

是的,除非你提交交易,否则你不会在数据库中看到任何结果。执行完所有插入后执行此操作。

相关问题