我尝试通过python将许多不同类型的列表插入SQL Server的表中。但这给了我字符串格式的错误(我认为)。我尝试了不同的方法,但仍然找不到一种同时执行带有数据列表的插入语句的方法。
print(type(InstanceGuid)) //uniqueIdentifier column in Table
print(type(InstanceName)) //varchar(255) column in table
print(type(ScoreList)) //float column in table
输出:
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
现在,我正在尝试的是:
config.py
import os
from easydict import EasyDict
INSERT = EasyDict()
INSERT.FIELDS = ['InstanceGuid', 'InstanceName', 'Score', 'Timerun']
TEST.INSERT_TABLE = 'xxxxxxxxxxx'
TEST.IP = 'xxx.xxxx.xxx.xx'
TEST.DB_NAME = 'xxxx'
TEST.USERNAME = 'xxxxx'
TEST.PWD = 'xxxxxxxxxx'
Insert.py
def InsertTable():
query = 'INSERT into '
query += TEST.INSERT_TABLE
query += '[' + INSERT.FIELDS[0] + '], '
query += '[' + INSERT.FIELDS[1] + '], '
query += '[' + INSERT.FIELDS[2] + '], '
# query += '[' + INSERT.FIELDS[3] + '] '
query += 'values '
query += '(%s,%s,%s)%'
return query
def storeData(InstanceGuid, InstanceName, ScoreList):
InstanceGuid = np.array(InstanceGuid)
InstanceName = np.array(InstanceName)
print(type(InstanceGuid))
print(type(InstanceName))
print(type(ScoreList))
with pytds.connect(TEST.IP, TEST.DB_NAME, TEST.USERNAME, TEST.PWD) as conn:
cursor = conn.cursor()
if conn == False:
print("Error, did not connect to the database")
else:
print("Connected to DB for Insertion")
query = InsertTable()
cursor.executemany(query +
InstanceGuid, InstanceName, ScoreList)
cursor.execute("COMMIT")
上面的方法在运行时给出错误:
错误:
TypeError: must be str, not UUID
编辑:
我读到某处executemany()期望列表而不是numpy数组,在传递列表后,它给出了错误:
operation = operation % tuple(names) ValueError: incomplete format
代码更改为:
def InsertTable():
query = 'INSERT into '
query += TEST.INSERT_TABLE
query += '[' + INSERT.FIELDS[0] + '], '
query += '[' + INSERT.FIELDS[1] + '], '
query += '[' + INSERT.FIELDS[2] + '], '
query += '[' + INSERT.FIELDS[3] + '] '
query += 'values '
query += '(%s,%s,%s,%s)%'
return query
with pytds.connect(TEST.IP, TEST.DB_NAME, TEST.USERNAME, TEST.PWD) as conn:
cursor = conn.cursor()
if conn == False:
print("Error, did not connect to the database")
else:
print("Connected to DB for Insertion")
query = InsertTable()
cursor.executemany(query,
(InstanceGuid, InstanceName, ScoreList, datetimeList))
cursor.execute("COMMIT")
print("Inserted Successfully")