[英]How to export a CSV to sql server database properly?
I'm trying to export a CSV file to an sql server database. 我正在尝试将CSV文件导出到sql服务器数据库。 I checked some questions on StackOverflow but none worked for me.
我检查了关于StackOverflow的一些问题,但没有一个对我有用。 Below is my code:
下面是我的代码:
import csv
import pymssql
connection = pymssql.connect(server='testdb.mammoth.io', user='mammoth',
password='jugular$35', database='samplelivedb', port=1433)
cur = connection.cursor()
cur.execute('create table sometable1(col1 varchar(20), col2 varchar(20))')
with open('batch1.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
table_name = 'sometable1'
columns = next(reader)
query = 'insert into {0}({1}) values ({2})'
query = query.format(table_name, ','.join(columns), ','.join('?' * len(columns)))
print(query) # INSERT INTO sometable1(one1, two1) values(?,?)
print("query is {0}".format(query))
for data in reader:
print(data) # ['b1col1', ' b1col1']
cur.execute(query, data)
connection.commit()
connection.close()
I'm getting an error that "ValueError: 'params' arg () can be only a tuple or a dictionary." 我收到一个错误,提示“ ValueError:'params'arg()只能是元组或字典。”
Now if i modify 现在,如果我修改
"cur.execute(query, data)"
to "cur.execute(query, data)"
到
"cur.execute(query, tuple(data))"
It gives another error : 它给出了另一个错误:
"pymssql.ProgrammingError: (102, b"Incorrect syntax near '?'.DB-Lib error message 20018, severity 15:\\nGeneral SQL Server error: Check messages from the SQL Server\\n")"
““ pymssql.ProgrammingError:(102,b“'?'附近语法不正确。.DB-Lib错误消息20018,严重性15:\\ n常规SQL Server错误:检查来自SQL Server的消息\\ n”)
What is the correct way to export csv to an sql server? 将csv导出到sql服务器的正确方法是什么?
I'm pretty sure your data = next(reader)
, is not supposed to be there, but only the columns = next(reader)
. 我很确定您的
data = next(reader)
不应存在,而只有columns = next(reader)
。 I have a working example here; 我这里有一个可行的例子。
with open ('example.csv', 'r') as f:
reader = csv.reader(f)
columns = next(reader)
query = 'INSERT INTO exampleTable({0}) values({1})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))
cursor = connection.cursor()
for data in reader:
cursor.execute(query, data)
cursor.commit()
connection.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.