【问题标题】:pyodbc - Bulk insert with some column values from CSVpyodbc - 使用 CSV 中的一些列值批量插入
【发布时间】:2021-02-11 14:54:01
【问题描述】:

如何执行批量插入,只有部分列从 CSV 文件中获取数据?

我的代码目前是这样的(对糟糕的伪代码表示歉意):

        with open("some_csv_file", "r") as csvFile:
            # load csv data
    
            for row in csvFile:
                column1_data = row[0]
                column2_data = row[1]
                column3_data = row[2]
        
                # how to bulk insert this?? All data is the same except data loaded from csv
                pyodbc.execute("INSERT INTO some_table(Code, column1, column2, column3, 
                some_other_column, some_other_column) VALUES(?, ?, ?, ?, ?, ?)", 'xy', column1_data, column2_data, column3_data, 'abc', 123)
        
                pyodbc.commit()    

          pyodbc.close()

我已经看到其他指向 pyodbc“executemany”的答案,但我正在努力弄清楚如何为发生变化的特定列加载 csv 数据

谢谢

【问题讨论】:

    标签: python sql pyodbc


    【解决方案1】:

    一种方法是将您的 SQL 语句变成一个插入许多行的语句。这是格式:

    INSERT INTO some_table (Col1name, Col2name, Col4name)
    VALUES
    (Row1Col1, Row1Col2, Row1Col4),
    (Row2Col1, Row2Col2, Row2Col4)
    

    看到这个帖子: Inserting multiple rows in a single SQL query?

    在您当前的代码结构中执行此操作:

    #make SQL statement with insert many
    sql = "INSERT INTO some_table (Col1name, Col2name, Col3name) "
    sql += "VALUES " 
    for row in CSVfile:
        sql += "(%s, %s, %s), " % (row[0], row[1], row[2])
    
    # chop of the last comma from the sql insert statement
    sql = sql[0:-2]
    
    # insert like normal
    pyodbc.execute(sql)
    

    【讨论】:

    • “我喜欢 SQL 注入!” - 小鲍比桌 :)
    • 是的,可能不应该在公共环境中使用它
    【解决方案2】:

    对于.executemany(),您的参数值应该是一个元组列表,每个元组代表一行。你可以这样做:

    >>> fake_csv_file = [['col1_val1', 'col2_val1'], ['col1_val2', 'col2_val2']]
    >>> param_data = []
    >>> for row in fake_csv_file:
        param_data.append((row[0], row[1], 'gord', 'was', 'here'))
    >>> from pprint import pprint
    >>> pprint(param_data)
    [('col1_val1', 'col2_val1', 'gord', 'was', 'here'),
     ('col1_val2', 'col2_val2', 'gord', 'was', 'here')]
    

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 1970-01-01
      • 2019-11-27
      • 2011-08-07
      • 2015-06-20
      相关资源
      最近更新 更多