具有返回值

时间:2017-12-30 14:32:23

标签: python sql-server sql-server-2014 pyodbc

我正在使用MS SQL Server 2014.我有以下代码:

import pyodbc, time
cnxn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};SERVER=192.xxx.xxx.xxx;DATABASE=test;UID=xx;PWD=xxxxx')
cursor = cnxn.cursor()
# cursor.fast_executemany = True
values = [(x,  "one_{0}".format(x), "ONE_{0}".format(x), 100) for x in range(300000)]

cursor.execute("""
CREATE TABLE employees
( id INT NOT NULL PRIMARY KEY,
  last_name VARCHAR(50) NOT NULL,
  first_name VARCHAR(50),
  salary MONEY
);
""")
cursor.commit()

t1 = time.time()

cursor.executemany("""
MERGE employees USING ( 
VALUES 
    (?, ?, ?, ?)
) AS vals (id, last_name, first_name, salary)
ON employees.id = vals.id
WHEN MATCHED THEN
    UPDATE SET 
    last_name = vals.last_name,
    first_name = vals.first_name,
    salary = vals.salary
WHEN NOT MATCHED THEN
    INSERT (id, last_name, first_name, salary)
    VALUES (vals.id, vals.last_name, vals.first_name, vals.salary)
OUTPUT inserted.id, inserted.last_name, inserted.first_name, inserted.salary;
""", values )
cursor.commit()

t2 = time.time()
print(t2 - t1)

此处,如果在不启用fast_executemany的情况下衡量上述代码段的效果,则需要35-40秒。如果我启用fast_executemany,那么它只需要500毫秒。

如果我尝试将结果提取为cursor.fetchmany()cursor.fetchall();它给出了一个错误:

---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
<ipython-input-10-d84781edf8ac> in <module>()
----> 1 cursor.fetchmany()

ProgrammingError: No results.  Previous SQL was not a query.

我想要返回上述upsert行为的值。在上面的代码片段中,我使用了300000个样本。这是我的正常情况。

是否可以使用MSSQL Server 2014和pyodbc驱动程序?在MSSQL Server中实现所需结果的任何其他方法吗?

0 个答案:

没有答案