【问题标题】:Load csv into mysql using Python syntax error [duplicate]使用Python语法错误将csv加载到mysql中[重复]
【发布时间】:2014-07-25 03:55:33
【问题描述】:

我有一个具有以下结构的 TSV 文件:

#DAteTime    Userid    tweet (each separated by \t)
2009-06-07 02:07:41 http://twitter.com/hokiepokie728    @fabro84 'Before the Storm' is a new song from the Jonas Brothers that is going to be on their new album. miley has a duet with nick on it!
2009-06-07 02:07:42 'http://twitter.com/annieng'    is in LA now

如何使用 python 将此文件导入名为tweet 的 MySQL 表中?我有以下表结构:

1   DT  datetime
2   USER    varchar(141)    
3   TWEET   varchar(141)    
4   ID  bigint(20)          AUTO_INCREMENT

【问题讨论】:

  • 嗯,文件大小约为 3 GB。我正在尝试的查询是: import MySQLdb db = MySQLdb.connect("localhost","root","", "TWEETS" ) sql = """LOAD DATA LOCAL INFILE 'sample.txt' INTO TABLE tweet FIELDS TERMINATED BY '\t' 由 '\n' 终止的行可选地由 '\' 封闭由 '\\' (DT,USER,TWEET)""" cursor = db.cursor() 尝试:cursor.execute(str(MySQLdb. escape_string(sql))) #cursor.execute(sql) db.commit() except MySQLdb.IntegrityError: db.rollback() logging.warn("Failed to insert values") db.close()

标签: python mysql csv


【解决方案1】:

使用 mysql-connector-python 1.2.2 你可以这样做

import mysql.connector
from mysql.connector.constants import ClientFlag

cnx = mysql.conector.connect(client_flags=[ClientFlag.LOCAL_FILES], ....)

cur = cnx.cursor()
cur.execute("LOAD DATA LOCAL INFILE '</path/to/data/file>' INTO "
            "TABLE tweet")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2015-01-10
    • 2013-05-21
    • 2020-10-30
    • 2012-04-26
    • 2013-01-17
    相关资源
    最近更新 更多