【问题标题】:Data is not inserted MSSQL Python数据未插入 MSSQL Python
【发布时间】:2021-10-27 14:22:01
【问题描述】:

我正在编写一个 python 脚本来将文本文件添加到 MSSQL 表中。使用pyodbc,我正在做。数据不会插入结果中。运行时没有报错。

这是我的代码,

import pyodbc
import os
from pathlib import Path
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=LAPTOP-LMBL29RS;DATABASE=mydb;UID=sa;PWD=123456')
cursor = cnxn.cursor()
path = 'testfiles'
files = os.listdir(path)
for f in files:
    filepath = path +'/'+ f
    filename = os.path.basename(path+'/'+filepath)
    with open(filepath) as fp:
        lines = fp.read().splitlines()
    with open(filepath, "r") as fp:
        count = 0;
        for line in lines:
            dataarr=[]
            if (count>0):
                dataarr = line.split(',')
                if(len(dataarr)==8):
                    print(dataarr[3])
                    query = ('INSERT INTO final_tbl("Date","Open","High","Low","Close","Volume","OpenInt","filename") '
                         'VALUES(?,?,?,?,?,?,?,?)')
                    cursor.execute(query, dataarr[0],dataarr[1],dataarr[2], dataarr[3], dataarr[4], dataarr[5],dataarr[6],dataarr[7])
            count = count+1
            #print(dataarr)

【问题讨论】:

  • 您似乎缺少commit
  • 我想我没有。查询中使用了 8 列,与使用的提交数相同。

标签: python sql reporting-services pyodbc


【解决方案1】:

循环完成后,您错过了对 cnxn.commit() 的调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多