I can access my SQL Server via SQL Server Mgmt Studio located at
<IP_ADDRESS> with credentials:
<USERID>
<PWD>
Using pycharm with Anaconda 2.7 as the interpreter my code is:
import pyodbc as p
server = '<IP_ADDRESS>'
database = 'listOfDBs/DB'
username = '<USERID>'
password = '<PWD>'
print ("DB CONNECT ATTEMPT")
try:
cnxn = p.connect(
'DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
print ("SUCCESS")
except Exception as e:
print ("Error: " + str(e))
My SQL Server is setup as:
ListOfDBs/DB
Folder1
Folder2
Folder3
Folder3
How do I connect to DB in ListOfDBs?
If I do:
Server = "XX.XXX.XXX/listOfDbs"
Database = "DB"
I get :
('08001', u'[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
If I do:
Server = "XX.XXX.XXX"
Database = "listOfDBs/DB"
I get:
('42000', u'[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "listOfDBs/DB" requested by the login. The login failed. (4060) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "listOfDBs/DB" requested by the login. The login failed. (4060)')
How do I do this? I am using Pycharm community version.
Related
I have a local db (localdb\Local_SAR) with a database "master":
I'm trying to connect to it using pyodbc:
server_local = '(local)'
SAR_connection_string_local = 'Driver=SQL Server;Server=%s;Database=master;Trusted_Connection=yes;' %(server_local)
cnxn = pyodbc.connect(SAR_connection_string_local)
cursor = cnxn.cursor()
I get error:
OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][Shared Memory]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][Shared Memory]ConnectionOpen (Connect()). (2)')
I've tried:
server_local = '(localdb\Local_SAR)'
server_local = '(localhost)'
server_local = 'localhost'
server_local = 'local'
And get the same error.
If I use a non local server it works, e.g:
server_local = 'SQLDEV\DB1'
EDIT:
I've managed to make a connection in Powershell using:
PS C:\Program Files\Microsoft SQL Server\130\Tools\Binn> sqlcmd -S "(localdb)\Local_SAR" -E
Which gives:
1> select 'hello'
2> go
-----
hello
(1 rows affected)
Still not sure how to do it in my python script. Maybe because of the PATH?
I can do a df.to_slq on my local instance of SQL Server just fine. I am getting stuck when trying to do the same df.to_sll using Python and Azure SQL Server. I thought it would essentially be done like this.
import urllib.parse
params = urllib.parse.quote_plus(
'Driver=%s;' % '{ODBC Driver 17 for SQL Server}' +
'Server=%s,1433;' % 'ryan-server.database.windows.net' +
'Database=%s;' % 'ryan_sql_db' +
'Uid=%s;' % 'UN' +
'Pwd={%s};' % 'PW' +
'Encrypt=no;' +
'TrustServerCertificate=no;'
)
from sqlalchemy.engine import create_engine
conn_str = 'mssql+pyodbc:///?odbc_connect=' + params
engine = create_engine(conn_str)
connection = engine.connect()
connection
all_data.to_sql('health', engine, if_exists='append', chunksize=100000, method=None,index=False)
That is giving me this error.
OperationalError: (pyodbc.OperationalError) ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\r\n (10060) (SQLExecDirectW); [08S01] [Microsoft][ODBC Driver 17 for SQL Server]Communication link failure (10060)')
[SQL: INSERT INTO health ([0], [Facility_BU_ID], [Code_Type], [Code], [Description], [UB_Revenue_Code], [UB_Revenue_Description], [Gross_Charge], [Cash_Charge], [Min_Negotiated_Rate], [Max_Negotiated_Rate], etc., etc., etc.
I found this link today:
https://learn.microsoft.com/en-us/sql/machine-learning/data-exploration/python-dataframe-sql-server?view=sql-server-ver15
I tried to do something similar, like this.
import pyodbc
import pandas as pd
df = all_data
# server = 'myserver,port' # to specify an alternate port
server = 'ryan-server.database.windows.net'
database = 'ryan_sql_db'
username = 'UN'
password = 'PW'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# Insert Dataframe into SQL Server:
for index, row in df.iterrows():
cursor.execute(all_data.to_sql('health', cnxn, if_exists='append', chunksize=100000, method=None,index=False))
cnxn.commit()
cursor.close()
When I run that, I get this error.
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
What I'm really hoping to to is df.to_sql, not Insert Into. I am working in Spyder and trying to send the data from my local machine to the cloud.
I read the two links below, and got it working.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-set-database-firewall-rule-azure-sql-database?view=azuresqldb-current
https://www.virtual-dba.com/blog/firewalls-database-level-azure-sql/
Basically, you need to open your command window on your local machine, enter 'ipconfig', and grab two IP addresses. Then, enter those into SQL Server in Azure.
EXECUTE sp_set_database_firewall_rule
N'health',
'192.0.1.1',
'192.0.0.5';
Finally, run the small script below, in SQL Server, to confirm that the changes were made correctly.
USE [ryan_sql_db]
GO
SELECT * FROM sys.database_firewall_rules
ORDER BY modify_date DESC
I wasn't sure what to title my post, if you have a better idea, feel free to edit the title.
I have not used SQL Alchemy before and the documentation that I have looked at located in the following places, is not helpful:
Connecting to SQL Database Using SQL Alchemy in Python
Tutorial Point
Here is the code I am using:
import sqlalchemy as sal
from sqlalchemy import create_engine
#Here are the parameters I am using:
- server = 'Q-20/fake_example'
- database = 'AdventureWorks2017'
- driver = 'ODBC Driver 17 for SQL Server'
- trusted_connection='yes'
DATABASE_CONNECTION = 'mssql+pyodbc://#server = ' + server + '/database = ' + database + '?trusted_connection = ' + trusted_connection + '&driver=' + driver
engine = sal.create_engine(DATABASE_CONNECTION)
All of that seems to work fine without any problems; however, when I add this line:
connection=engine.connect()
I get the following error message:
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001',
'[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes
Provider: Could not open a connection to SQL Server [53]. (53)
(SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL
Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17
for SQL Server]Invalid connection string attribute (0); [08001]
[Microsoft][ODBC Driver 17 for SQL Server]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.
(53)')
I am not sure what is wrong with what I am doing, does anyone have any suggestions?
What I have tried so far:
I have confirmed that SQL Server is configured to allow remote connections. I did this check by following the instructions here
Removing the "#" sign before the server, but this just generated the same error message.
I figured out part of what I needed to do. I needed to change my parameters.
Old Parameters:
server = 'Q-20/fake_example'
database = 'AdventureWorks2017'
driver = 'ODBC Driver 17 for SQL Server'
trusted_connection='yes'
New Parameters:
server = 'Q-20'
database = 'AdventureWorks2017'
driver = 'SQL+SERVER+NATIVE+CLIENT+11.0'
trusted_connection='yes'
This is what my code ultimately looked like:
database_connection = 'mssql+pyodbc://Q-20/AdventureWorks2017?trusted_connection=yes&driver=SQL+SERVER+NATIVE+CLIENT+11.0'
I am connecting to a SQL Server hosted on a remote desktop using Windows server through VBA with this code:
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open Connection
objMyConn.ConnectionString = "Provider=SQLOLEDB.1;User ID=sa;Password=xxxxx;Persist Security Info=True;Initial Catalog=databaseName;Data Source=192.168.1.xxx;"
objMyConn.Open
Currently trying to use python to connect to the same SQL Server database with this code:
import pyodbc
server_name='192.168.1.xxx'
db_name='databaseName'
username='sa'
password='xxxxx'
conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};'
'Server=server_name;'
'Database=db_name;'
'UID=username;'
'PWD=password;'
'Trusted_Connection=yes;')
cursor=conn.cursor()
TRACEBACK:
File "x/test.py", line 6, in <module>
conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};'
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 11 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 11 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 11 for SQL Server]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. (53)')
You should omit argument trusted_connection since you are providing UID and PWD. Trusted_connection fills UID and PWD values with your current windows user values so it is probably reserved for a local connection within the host.
I belive connection string should look like this:
'DRIVER={ODBC Driver 11 for SQL Server};'
'Server=server_name;'
'Database=db_name;'
'UID=username;'
'PWD=password;'
I have been trying to connect to Microsoft SQL Server. I have an ODBC connection set up and the test is successful. I am not using Windows Authentication to connect to SQL Server but it keep getting this error:
Cannot be used with Windows authentication
InterfaceError: ('28000', '[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (18452) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (18452); [28000] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)')
Here is my code:
import pyodbc
cnxn = pyodbc.connect(Driver='{SQL Server}',
Server='servername.abc.xyz.co.com',
username = 'user_xyz',
password = 'abcdfgh')
I am using Windows 7. Please help me debug this problem
Thanks
I was able to solve this by defining the dsn connection as below:
dsn="DRIVER={SQL
SERVER};server=ip_address_here;database=db_name_here;uid=user;pwd=password"
This worked and I was able to connect and query the sql server.
This is how I do it and it works:
import pyodbc
server_name = "server_name"
db_name = "db_name"
server = "Server="+str(server_name)
db = "Database="+str(db_name)
key = "Driver={SQL Server Native Client 11.0};"+server+";"+db+";"+"Trusted_Connection=yes;"
cnxn = pyodbc.connect(key)