Cannot Connect Using SQL Alchemy Unknown MySQL server host - python

I am trying to connect to a MySQL database on my local machine. I am able to connect using MySQL Workbench, but when I try to use sqlalchemy it does not allow me to connect.
The user has the correct permissions. I can connect using MySQL bench so I know the credentials are correct.
engine = create_engine('mysql://username:password!# ***.***.***.**:3306/ceesmart')
connection = engine.connect()
OperationalError: (_mysql_exceptions.OperationalError) (2006, "Unknown MySQL server host ' ..*.' (2)") (Background on this error at: http://sqlalche.me/e/e3q8)

I don't know if it was on copying and pasting here, but you have an "space" between the # and the first octect:
# ***.*
^ here
That could make the engine to try to resolve it as a DNS name instead of an IP address, therefore, raising Unknown Host exception

Related

(pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query)

I am having problem querying to a MariaDB database that is hosted on a Virtual Machine. I am using the dataset Python module.
This is my code:
import dataset
db = dataset.connect("mysql+pymysql://....")
Q = "select * from mytable Limit 1"
print(db.query(Q))
However I would get this error message:
(pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server
during query ([WinError 10060] 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)') (Background on this error at: http://sqlalche.me/e/e3q8)
I have tried to configure the timeout variables such as; connect_timeout, wait_timeout etc within the my.cnf file and sending a very simple query, but the issue still exist.
Any solutions or suggestions would be highly appreciated. Thank you

Connecting to CloudSQL from Dataflow in Python

I'm trying to connect to CloudSQL with a python pipeline.
Actual situation
I can do it without any problem using DirectRunner
I can not connect using DataflowRunner
Connection function
def cloudSQL(input):
import pymysql
connection = pymysql.connect(host='<server ip>',
user='...',
password='...',
db='...')
cursor = connection.cursor()
cursor.execute("select ...")
connection.close()
result = cursor.fetchone()
if not (result is None):
yield input
The error
This is the error message using DataflowRunner
OperationalError: (2003, "Can't connect to MySQL server on '<server ip>' (timed out)")
CloudSQL
I have publicIP (to test from local with directrunner) and I have also trying to activating private IP to see if this could be the problem to connect with DataflowRunner
Option2
I have also tried with
connection = pymysql.connect((unix_socket='/cloudsql/' + <INSTANCE_CONNECTION_NAME>,
user='...',
password='...',
db='...')
With the error:
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")
Take a look at the Cloud SQL Proxy. It will create a local entrypoint (Unix socket or TCP port depending on what you configure) that will proxy and authenticate connections to your Cloud SQL instance.
You would have to mimic the implementation of JdbcIO.read() in Python as explained in this StackOverflow answer
With this solution I was able to access to CloudSQL.
For testing purpose you can add 0.0.0.0/0 to CloudSQL publicIP without using certificates
I created a example using Cloud SQL Proxy inside the Dataflow worker container, connection from the Python pipeline using Unix Sockets without need for SSL or IP authorization.
So the pipeline is able to connect to multiple Cloud SQL instances.
https://github.com/jccatrinck/dataflow-cloud-sql-python
There is a screenshot showing the log output showing the database tables as example.

Connect to database in Remote machine - python - SQL Server

I have a database server which can be accessed by Remote desktop login to the server machine. This is what we do manually:
Login with Remote desktop to the machine from local.
Open Database client in the connected machine.
Then connect to database.
Now, I need to connect to this DB using python.
What I already tried?.. below works for all DB that I connect without remote.
conn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=<server name>;database=<DB name>;UID=<user>;PWD=<pwd>")
Error:
pyodbc.OperationalError: ('08001', u'[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]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)')
before you use below code in python, you have to follow this guide to configure your SQL server https://knowledgebase.apexsql.com/configure-remote-access-connect-remote-sql-server-instance-apexsql-tools/
note: 1434 is my UDP port in Inbound Rules
conn = pyodbc.connect('DRIVER={SQL Server};SERVER = your_server_ipv4,1434;DATABASE=B_SQL;UID=sa;PWD=123456;')
cursor = conn.cursor()
#cursor.execute("DELETE FROM my_table")
for index, row in df.iterrows():
#print(row)
cursor.execute("INSERT INTO my_table([Name],[Volume]) values(?,?)", row['Name'], row['Volume'])
conn.commit()
cursor.close()
conn.close()
it works very well for me!
Can you connect to your SQL Server from another application, including Excel?
If you cannot, I would check the following:
Remote into the server and open the SQL Server Configuration Manager.
There should be a section labeled SQL Server Network Configuration that will have an entry for "Protocols for ". If you click on that entry, you will see which protocols are enabled for your database.
Click on TCP/IP and select properties. Under the IP addresses, each IP listed may need to have a port listed.
Once that is done, make sure that port is enabled in your firewall on the server for both Inbound and Outbound.
When I managed a SQL-driven application, we normally got the Named Pipes error when there was other connection issues such as firewall issues or the SQL Server Browser or instance not running.
If this is not sufficient to resolve the issue, there are a ton of other options on MSSQL Tips.

python connection with SQL server

I used the pyodbc and pypyodbc python package to connect to SQL server.
Drivers used anyone of these ['SQL Server', 'SQL Server Native Client 10.0', 'ODBC Driver 11 for SQL Server', 'ODBC Driver 13 for SQL Server'].
connection string :
connection = pyodbc.connect('DRIVER={SQL Server};'
'Server=aaa.database.windows.net;'
'DATABASE=DB_NAME;'
'UID=User_name;'
'PWD=password')
now I am getting error message like
DatabaseError: (u'28000', u"[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user
But I can connect to the server through the SQL server management studio.
its on SQL Server Authentication, Not Windows Authentication.
Is this about python package and driver issue or DB issue??? how to solve?
You can add Trusted_Connection=NO; in your connection string after the password
I see you have no port defined in your script.
The general way to connect to a server using pyodbc ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort}, where DBName is your database name, DBUser is the username used to connect to it, DBPass is the password, DBHost is the URL of your database, and DBPort is the port you use to connect to your DB.
I use MS SQL so my port is 1433, yours might be different.
I've had this issue just today, and that fixed it.
The problem is not driver issue, you can see the error message is DatabaseError: Login failed for user, it means this problem occurs if the user tries to log in with credentials that cannot be validated. I suspect you are login with your windows Authentication, if so, use Trusted_Connection=yes instead:
connection = pyodbc.connect('DRIVER={SQL Server};Server=aaa.database.windows.net;DATABASE=DB_NAME;Trusted_Connection=yes')
For more details, please refer to my old answer about the difference of SQL Server Authentication modes.
I think problem because of driver definition in your connection string. You may try with below.
connection = pyodbc.connect('DRIVER={SQL Server Native Client 10.0}; Server=aaa.database.windows.net; DATABASE=DB_NAME; UID=User_name; PWD=password')
I applied your connection string and updated it with my server connections details and it worked fine.
Are you sure your are passing correct user name and password ?
Login failed implies connection was established successfully, but authentication didn't pass.

Cannot connect to SQL\Express with pyodbc/pymssql and Robot Framework

I'm having issues connecting to a working SQL\Express database instance using Robot Framework's DatabaseLibrary.
If I use either Connect To Database with previously defined variables or Connect To Database Using Custom Params with a connection string, I get the following results:
pyodbc: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
pymssql:: InterfaceError: Connection to the database failed for an unknown reason.
The connection string I'm using is the following: 'DRIVER={SQL Server};SERVER=localhost\SQLExpress;UID=sa;PWD=mypass;DATABASE=MyDb'
I copied several examples from guides and tutorials and all of them yield the same result, so my guess is that there is something wrong on my end, but I just can't figure out what. I can access the database using the Microsoft SQL Server Management Studio just fine, so the database is running.
Any guidance will be greatly appreciated!
I was able to connect using #Goralight approach: Connect To Database Using Custom Params pymssql ${DBConnect} where ${DBConnect} contained database, user, Password, host and port

Categories