尝试使用pymssql连接到数据库时出现KeyError

时间:2019-10-21 11:50:43

标签: sql-server python-3.x pymssql

以下代码尝试使用pymssql连接到mssql数据库。我有一个CSV文件,我正在尝试将所有行推送到mssql数据库中的单个数据表中。打开CSV文件后尝试执行代码时,出现“ KeyError”错误。

import csv
import pymssql
conn = pymssql.connect(host="host name", 
                       database="dbname", 
                       user = "username",
                       password = "password")

cursor = conn.cursor()
if(conn):
    print("True")
else:
    print("False")

with open ('path to csv file', 'r') as f:
    reader = csv.reader(f)
    columns = next(reader) 
    query = "INSERT INTO Marketing({'URL', 'Domain_name', 'Downloadables', 'Text_without_javascript', 'Downloadable_Link'}) VALUES ({%s,%s,%s,%s,%s})"
    query = query.format(','.join('[' + x + ']' for x in columns), ','.join('?' * len(columns)))
    cursor = conn.cursor()
    for data in reader:
        cursor.execute(query, tuple(data))
    cursor.commit()

以下是我得到的错误:

KeyError: "'URL', 'Domain_name', 'Downloadables', 'Text_without_javascript', 'Downloadable_Link'"

使用to_sql

file_path = "path to csv"
engine = create_engine("mssql://user:password@host/database") 

df = pd.read_csv(file_path, encoding  = 'latin')
df.to_sql(name='Marketing',con=engine,if_exists='append')

输出:

InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

1 个答案:

答案 0 :(得分:0)

我尝试了一切,从将要传递给元组的参数转换为原样传递,但没有帮助。以下是帮助我解决此问题的代码:

with open ('path to csv file', 'r') as f:
    for row in f:
        reader = csv.reader(f)
#        print(reader)
        columns = next(reader) 
#        print(columns)
        cursor = conn.cursor()
        for data in reader:
#            print(data)
            data = tuple(data)
#            print(data)
            query = ("INSERT INTO Marketing(URL, Domain_name, Downloadables, Text_without_javascript, Downloadable_Link) VALUES (%s,%s,%s,%s,%s)")
            parameters = data
#            query = query.format(','.join('?' * len(columns)))
            cursor.execute(query, parameters)
        conn.commit()

注意:与数据库部分的连接仍然与问题相同。