如何在insert语句中保留“\”?

时间:2013-06-04 09:39:11

标签: python mysql

我创建了简单的代码,以便寻找驱动器上的所有文件并将结果插入表中。但是,当它尝试插入时,代替在表中插入值y:\ somedir \ file.txt,代码插入y:somedirfile.txt。

如何插入和保留目录中的反斜杠?

Bellow,我正在使用的代码:

#!/usr/bin/env python
import time
import datetime
import re
import MySQLdb
import sys
import fnmatch
import os


def insert_db(sql):

    conn = None
    conn = MySQLdb.connect(host='somehost', db='somedb',
                          user='someuser', passwd='somepass',
                          )
    try:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        cursor.close()
    except MySQLdb.Error, e:
        conn.rollback()
        print "Error "
        print e.args
        sys.exit(1)


def read_file():
    matches = []
    for root, dirnames, filenames in os.walk('y:\\'):
        for loop in fnmatch.filter(filenames, '*.*'):
            Values = dict()
            filename =  os.path.join(root, loop)
            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filename)
            modtime = datetime.datetime.strptime(time.ctime(mtime), "%a %b %d %H:%M:%S %Y")
            fsize = os.stat(filename).st_size
            sql ="""insert into pvcs (date,name,size) values ('%(DATE)s',"%(FILE)s",'%(SIZE)s');
            """ % {'DATE':modtime,'FILE':filename,'SIZE':fsize}
            insert_db(sql)
            #print sql
            #time.sleep(5)

示例输出:

insert into pvcs (date,name,size) values ('2013-05-30 17:08:12',"y:\somedir\change.log",'2196815');

提前致谢

1 个答案:

答案 0 :(得分:1)

insert_db()中的

def insert_db(sql, data):
    ...
    cursor.execute(sql, data)

下面:

sql = "insert into pvcs (date,name,size) values (%s,%s,%s)"
data = (modtime, filename, fsize)
insert_db(sql, data)