【发布时间】:2019-10-03 13:39:48
【问题描述】:
我已经编写了一些 Python 代码,这些代码基本上将从一个数据库 (SQL Server 2008) 中获取数据并将其插入到另一个数据库 (MySQL) 中。我对 python 还很陌生,所以很难在我的代码中找到错误。
我的代码是:
import mysql.connector
import pyodbc
def insert_VPS(SageResult):
query = """
INSERT INTO SOPOrderReturn(SOPOrderReturnID,DocumentTypeID,DocumentNo,DocumentDate,CustomerID,CustomerTypeID,CurrencyID,SubtotalGoodsValue,TotalNetValue,TotalTaxValue,TotalGrossValue,SourceTypeID,SourceDocumentNo)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
try:
mydbVPS = mysql.connector.connect(
host="serveraddress",
user="username",
passwd="password;",
database="databse"
)
VPScursor = mydbVPS.cursor()
print(SageResult)
VPScursor.executemany(query, SageResult)
mydbVPS.commit()
except Exception as e:
print('InsertError:', e)
finally:
VPScursor.close()
mydbVPS.close()
def main():
selectQuery = """
SELECT TOP 1 [SOPOrderReturnID]
,[DocumentTypeID]
,[DocumentNo]
,[DocumentDate]
,[CustomerID]
,[CustomerTypeID]
,[CurrencyID]
,[SubtotalGoodsValue]
,[TotalNetValue]
,[TotalTaxValue]
,[TotalGrossValue]
,[SourceTypeID]
,[SourceDocumentNo]
FROM [Live].[dbo].[SOPOrderReturn]
"""
try:
mydbSage = pyodbc.connect('Driver={SQL Server};'
'Server=CRMTEST;'
'Database=Live;'
'UID=sa;'
'PWD=password;')
Sagecursor = mydbSage.cursor()
Sagecursor.execute(selectQuery)
SageResult = tuple(Sagecursor.fetchall())
mydbSage.commit()
except Exception as e:
print('MainError:', e)
finally:
Sagecursor.close()
mydbSage.close()
insert_VPS(SageResult)
if __name__ == '__main__':
main()
我得到的错误:
D:\xampp\htdocs\stripe\group\beta>sql-sync.py
((10447177, 0, '0000091897', datetime.datetime(2010, 8, 18, 0, 0), 186150, 1, 1, Decimal('18896.95'), Decimal('18896.95'), Decimal('3779.39'), Decimal('22676.34
'), 0, ''),)
InsertError: Failed executing the operation; Could not process parameters
我已经在一个更基本的脚本中测试了选择查询(但不是 INSERT 查询)和两个连接,这些都可以正常工作。任何人都可以看到这些问题吗?
【问题讨论】:
-
MySQL 在 SQL Server 等标识符周围使用反引号,而不是括号
[...]。 -
我已经用从插入查询中取出的括号更新了上面的代码(另一个是使用 SQL 服务器运行的)。我仍然遇到同样的错误。
-
可能是数据问题。在插入之前尝试打印 SageResult 以查看内容。
-
我添加了一个打印并更改了它,因此它只在选择中拉出一个结果,以便更容易查看。你能发现任何问题吗? (见上面的更新输出)
-
我怀疑
SageResult是pyodbc.Row对象的元组,mysql.connector可能不喜欢那些。请参阅 this answer 了解创建元组列表的方法。