【问题标题】:Python SQL data import - Backslash removed in the process of data import to data basePython SQL 数据导入 - 数据导入到数据库过程中去掉了反斜杠
【发布时间】:2018-10-16 07:21:18
【问题描述】:

我正在将字符串值导入数据库,问题是在导入过程中反斜杠被删除。所以我在数据库中有“\\”的地方出现了下面的“\”,而我有“\”的地方出现了“”。非常感谢任何帮助。

导入方法代码为:

         cnxn = MySQLdb.connect(host=entry_server_value, user=entry_user_value, passwd=entry_password_value, db=entry_dbName_value)
    columns_list = ""
    for column in columns:
        columns_list = columns_list + column
        if columns.index(column) is not (len(columns)-1):
            columns_list = columns_list + ','

    for line in csv.reader(open(full_file_path)):
        cursor = cnxn.cursor()
        values = ""
        for x in line:
            values = values + "'" + str(x) + "'"
            if line.index(x) is not (len(line)-1):
                values = values + ','

        # In case last character is comma remove 
        if values[-1:] is ',':
            values = values[:-1]

        mysql_q = 'SET SQL_SAFE_UPDATES = 0;insert into ' + entry_dbName_value + '.' + file_name + \
              ' (' + columns_list + ') VALUES(' + values + ');SET SQL_SAFE_UPDATES = 1;'
        cursor.execute("%r"%mysql_q)
        cursor.close()
        cnxn.commit()

【问题讨论】:

    标签: python sql data-import


    【解决方案1】:

    MySQLdb(和其他符合 Python 的 DB-API 标准的包)提供了一种参数替换方法,可以自动处理字符串转义。使用它比尝试手动构造插入值更好(如果您从不受信任的来源插入数据,它也更安全)。

    对于 MySQLdb,替换字符串是 '%s'。

    您可以这样创建语句:

    stmt = """INSERT INTO mytable (col1, col2) VALUES (%s, %s);"""

    然后像这样执行:

    cursor.execute(stmt, ('foo', 'bar'))

    或者您可以在单个语句中插入多行:

    cursor.executemany(stmt, [('foo', 'bar'), ('baz', 'quux')])

    您的代码应如下所示:

    mysql_q = 'SET SQL_SAFE_UPDATES = 0;insert into ' + entry_dbName_value + '.' + file_name + \
              ' (' + columns_list + ') VALUES({});SET SQL_SAFE_UPDATES = 1;'
    for line in csv.reader(open(full_file_path)):
        cursor = cnxn.cursor()
        subs = ','.join('%s' for _ in line)
        stmt = mysql_q.format(subs)
        cursor.execute(stmt, line)
        cursor.close()
        cnxn.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多