简体   繁体   中英

Can not connect to SQL Server via Python

Here is my code below that I'm just trying to send df to the server, the same code was working when I use the local server without user and pass, I've tried all the combination. Is there any other way around or I'm missing something?

Additional Note: SQL server is connected through company VPN is it affected?

import pandas as pd
from fast_to_sql import fast_to_sql as fts
df=pd.read_excel(r'C:\Users\han.37\Desktop\test\Copy of 01012020.xlsx')
#send to SQL server
sql_conn = (
r'DRIVER={SQL Server Native Client 11.0};'
r'SERVER=GRATHDB03\REPLICA;'
r'DATABASE=DATAWRHS-PM;'
r'Trusted_Connection=yes;'
r'UID=EMEA\han.37;'
r'PWD=****;'
)
conn_db = pyodbc.connect(sql_conn)

create_statement = fts.fast_to_sql(df, "Contact Patterntest2", conn_db, if_exists="append", temp=False)

conn_db.commit()
conn_db.close()

And the error is;

OperationalError: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. (-1) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (-1)')

I do it like this.

import pypyodbc 
cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=server_name\\SQLEXPRESS;"
                        "Database=TestDB;"
                        "Trusted_Connection=yes;")

#cursor = cnxn.cursor()
#cursor.execute("select * from Actions")
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Actions')

for row in cursor:
    print('row = %r' % (row,))


# with login creds


pyodbc.connect("Driver = {SQL Server Native Client 11.0};"               
               "Server = Server_Name;"
               "Database = Database_Name;"
               "username = User_Name;"
               "password = User_Password;"
               "Trusted_Connection = yes;")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM