嗨,我在Micorsoft Azure平台上使用的是SQL Server V17.3。我正在尝试将数据从python 3.7数据帧上传到我在sql server上的表测试。所以我写了下面的代码
import time
start_time = time.time()
import pyodbc
from sqlalchemy import create_engine
import urllib
dataToUpload=pd.read_csv("intermediate.csv")
params = urllib.parse.quote_plus(r'DRIVER=SQLServer};SERVER=nesbaexplsql001.database.windows.net;DATABASE=mydatabase;Trusted_Connection=False;Encrypt=True;uid=myuid;pwd=my password')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str)
dataToUpload.to_sql(name='test',con=engine, if_exists='append',index=False)
但是我收到错误消息
DBAPIError: (pyodbc.Error) ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver][SQL Server]Windows logins are not supported in this version of SQL Server. (40607) (SQLDriverConnect); [HY000] [Microsoft][ODBC SQL Server Driver][SQL Server]Windows logins are not supported in this version of SQL Server. (40607)') (Background on this error at: http://sqlalche.me/e/dbapi)
在执行to_sql时。我也尝试通过放置Trusted_Connection = yes并删除Encryption = True。但是我遇到了同样的错误。您可以指导我解决此问题吗?
答案 0 :(得分:0)
请参考我的示例代码:
import pyodbc
import csv
server = 'tcp:***.database.windows.net'
database = '***'
username = '***'
password = '***'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("select * from ***")
row = cursor.fetchone()
while row:
print(row[0])
row = cursor.fetchone()
mycsv = r'D:\insert.csv' # SET YOUR FILEPATH
with open (mycsv, 'r') as f:
reader = csv.reader(f)
columns = next(reader)
query = 'insert into <TABLE NAME>({0}) values ({1})'
query = query.format(','.join(columns), ','.join('?' * len(columns)))
cursor = cnxn.cursor()
for data in reader:
cursor.execute(query, data)
cursor.commit()
答案 1 :(得分:0)
在连接字符串中添加一条:
集成安全性= False;
希望这会有所帮助。