简体   繁体   English

如何让数据从 Python“提交”到 SQL Server?

[英]How do I get Data to 'commit' from Python to SQL Server?

I have a localhost SQL Server running and am able to connect to it successfully.我有一个本地主机 SQL Server 正在运行并且能够成功连接到它。 However, I am running into the problem of data not transfering over from temp csv files.但是,我遇到了数据未从临时 csv 文件传输过来的问题。 Using Python import pyodbc for Server connection.使用 Python import pyodbc 进行服务器连接。

I've tried with Python Import pymssql but have had worse results so I've stuck with pyodbc.我试过使用 Python Import pymssql 但结果更差,所以我坚持使用 pyodbc。 I've also tried closing the cursor each time or just at the end but not to any luck.我也尝试过每次或只是在结束时关闭光标,但没有任何运气。

Here is a piece of code that I am using.这是我正在使用的一段代码。 Towards the bottom are two different csv styles.底部是两种不同的 csv 样式。 One is a temp in which is used to fill the SQL Server table.一个是用于填充 SQL Server 表的临时文件。 The other is for my personal use to make sure I am actually gathering information at the moment but, in the long term will be removed so only the temp csv is used.另一个供我个人使用,以确保我目前确实在收集信息,但从长远来看将被删除,因此仅使用临时 csv。

@_retry(max_retry=1, timeout=1)
def blocked_outbound_utm_scada():
    # OTHER CODE EXISTS HERE!!!
    # GET Search Results and add to a temp CSV File then send to MS SQL Server
    service_search_results_str = '/services/search/jobs/%s/results?output_mode=csv&count=0' % sid
    search_results = (_service.request(_host + service_search_results_str, 'GET',
                                       headers={'Authorization': 'Splunk %s' % session_key},
                                       body={})[1]).decode('utf-8')
    with tempfile.NamedTemporaryFile(mode='w+t', suffix='.csv', delete=False) as temp_csv:
        temp_csv.writelines(search_results)
        temp_csv.close()
        try:
            cursor.execute("BULK INSERT Blocked_Outbound_UTM_Scada FROM '%s' WITH ("
                           "FIELDTERMINATOR='\t', ROWTERMINATOR='\n', FirstRow = 2);" % temp_csv.name)
            conn.commit()
        except pyodbc.ProgrammingError:
            cursor.execute("CREATE TABLE Blocked_Outbound_UTM_Scada ("
                           "Date_Time varchar(25),"
                           "Src_IP varchar(225),"
                           "Desktop_IP varchar(225));")
            conn.commit()
        finally:
            cursor.execute("BULK INSERT Blocked_Outbound_UTM_Scada FROM '%s' WITH ("
                           "FIELDTERMINATOR='\t', ROWTERMINATOR='\n', FirstRow = 2);" % temp_csv.name)
            conn.commit()
        os.remove(temp_csv.name)
    with open(_global_path + '/blocked_outbound_utm_scada.csv', 'a', newline='') as w:
        w.write(search_results)
    w.close()

I'm just trying to get the information into SQL Server but the code seems to be ignoring cursor.commit() .我只是想将信息输入 SQL Server,但代码似乎忽略cursor.commit() Any help is appreciated in figuring out what is wrong.在找出问题所在方面,我们将不胜感激。

Thanks in Advance!提前致谢!

Try it without the conn.commit .在没有conn.commit的情况下尝试。

I do not understand why or how does it work but it seems, as well to me, that pyodbc ignores the commit clause.我不明白它为什么或如何工作,但在我看来,pyodbc 似乎忽略了 commit 子句。

Try change autocommit parameter in pymssql.connect()尝试在 pymssql.connect() 中更改自动提交参数

conn = pymssql.connect(host=my_host, user=my_user, password=my_password, database=my_database, autocommit=True)
conn = pymssql.connect(host=my_host, user=my_user, password=my_password, database=my_database, autocommit=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM