Can you connect to a database on another pc? - python

I'm using MySQLdb for python, and I would like to connect to a database hosted on an other PC on the same network/LAN.
I tried the followings for host:
192.168.5.37
192.168.5.37:3306
http://192.168.5.37
http://192.168.5.37:3306
None of the above work, I always get the
2005, Unknown MySQL server host ... (0)
What might be the problem?
Code:
db = MySQLdb.connect(host="192.168.5.37", user = "root" passwd = "password", db = "test1")

You can use MySQL Connector/Python, a standardized database driver for Python.
You must provide username, password, host, database name.
import mysql.connector
conn = mysql.connector.connect(user=username, password=password,
host="192.168.5.37",
database=databaseName)
conn.close()
You can download it from: https://dev.mysql.com/downloads/connector/python/

The IP you posted are local IPs
Give it a try with your external IP (for example on this website)
https://www.whatismyip.com/
If it works with the external IP, then it's maybe a misconfiguration of your firewall.

Related

Getting Login Failed error with sqlalchemy+PYODBC when trying to connect to mssql DB server with another Domain credentials,but connected with Pymssql [duplicate]

I am trying to use Python to connect to a SQL database by using Window authentication. I looked at some of the posts here (e.g., here), but the suggested methods didn't seem to work.
For example, I used the following code:
cnxn = pyodbc.connect(driver='{SQL Server Native Client 11.0}',
server='SERVERNAME',
database='DATABASENAME',
trusted_connection='yes')
But I got the following error:
Error: ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]
Login failed for user 'DOMAIN\\username'. (18456) (SQLDriverConnect); [28000] [Microsoft]
[SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\\username'.
(18456)")
(Note that I replaced the actual domain name and user name with DOMAIN and username respectively, in the error message above.)
I also tried using my UID and PWD, which led to the same error.
Lastly, I tried to change the service account by following the suggestion from the link above, but on my computer, there was no Log On tab when I went to the Properties of services.msc.
I wonder what I did wrong and how I can fix the problem.
Connecting from a Windows machine:
With Microsoft's ODBC drivers for SQL Server, Trusted_connection=yes tells the driver to use "Windows Authentication" and your script will attempt to log in to the SQL Server using the Windows credentials of the user running the script. UID and PWD cannot be used to supply alternative Windows credentials in the connection string, so if you need to connect as some other Windows user you will need to use Windows' RUNAS command to run the Python script as that other user..
If you want to use "SQL Server Authentication" with a specific SQL Server login specified by UID and PWD then use Trusted_connection=no.
Connecting from a non-Windows machine:
If you need to connect from a non-Windows machine and the SQL Server is configured to only use "Windows authentication" then Microsoft's ODBC drivers for SQL Server will require you to use Kerberos. Alternatively, you can use FreeTDS ODBC, specifying UID, PWD, and DOMAIN in the connection string, provided that the SQL Server instance is configured to support the older NTLM authentication protocol.
I tried everything and this is what eventually worked for me:
import pyodbc
driver= '{SQL Server Native Client 11.0}'
cnxn = pyodbc.connect(
Trusted_Connection='Yes',
Driver='{ODBC Driver 11 for SQL Server}',
Server='MyServer,1433',
Database='MyDB'
)
Try this cxn string:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass')
http://mkleehammer.github.io/pyodbc/
I had similar issue while connecting to the default database (MSSQLSERVER). If you are connecting to the default database, please remove the
database='DATABASENAME',
line from the connection parameters section and retry.
Cheers,
Deepak
The first option works if your credentials have been stored using the command prompt. The other option is giving the credentials (UId, Psw) in the connection.
The following worked for me:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=yourServer;DATABASE=yourDatabase;UID=yourUsername;PWD=yourPassword')
import pyodbc #For python3 MSSQL
cnxn = pyodbc.connect("Driver={SQL Server};" #For Connection
"Server=192.168.0.***;"
"PORT=1433;"
"Database=***********;"
"UID=****;"
"PWD=********;")
cursor = cnxn.cursor() #Cursor Establishment
cursor.execute('select site_id from tableName') #Execute Query
rs = cursor.fetchall()
print(rs)
A slightly different use case than the OP, but for those interested it is possible to connect to a MS SQL Server database using Windows Authentication for a different user account than the one logged in.
This can be achieved using the python jaydebeapi module with the JDBC JTDS driver. See my answer here for details.
Note that you may need to change the authentication mechanism. For example, my database is using ADP. So my connection looks like this
pyodbc.connect(
Trusted_Connection='No',
Authentication='ActiveDirectoryPassword',
UID=username,
PWD=password,
Driver=driver,
Server=server,
Database=database)
Read more here
Trusted_connection=no did not helped me. When i removed entire line and added UID, PWD parameter it worked. My takeaway from this is remove

How to specifies database name in pyhdb

import pyhdb
connect = pyhdb.connect(
host="example.com",
port=30015,
user="user",
password="secret"
)
From the official explanation
Pyhdb only gives four parameters. Without the parameter database name, I can't understand how the system knows which database you want to connect to in this case?
And when i connect in this way, Program error:"pyhdb.exceptions.DatabaseError: authentication failed",
it looks like my password is wrong, so i let friends use JAVA(jdbc) to connect with four parameters,
it failed too, but if he add database name, it worked! so my parameters is right , and question is how to specify database name in pyhdb?
Or there are other ways to connect to Hana, Thankyou!
Looking at the __init__.py file of the pyhdb package shows that DATABASENAME is not supported when creating a connection:
[...]
def connect(host, port, user, password, autocommit=False):
conn = Connection(host, port, user, password, autocommit)
conn.connect()
return conn
[...]
The good news here is that pyhdb is not what you should be using to connect to HANA anyhow as it is the old and unsupported client library.
Use hdbcli instead as described in the documentation.
With hdbcli it's no problem at all to use the DATABASENAME:
from hdbcli import dbapi
connection =dbapi.connect(address="hxehost", port=39013, databasename="HXE", user="xxxxx", password="xxxxx")
cursor = connection.cursor()
cursor.execute("SELECT 'Hello, Python world' FROM DUMMY")
print(cursor.fetchone())
connection.close()

How to connect database from cPanel to Desktop in python

I am making an application in python - and need to connect to a web server database from the desktop.
How can I do this.
example:
if my site is xyz.com it's ip is 123.134.121.136 and my database name is xyz_code and name is xyz_alibaba and password is !##!#1&#a##
import MySQLdb as mdb
s_h = "123.134.121.136:3306"
s_u = "xyz_alibaba"
s_p = "!##!#1&#a##"
s_d = "softwar1_codexyz_code"
s_cn = mdb.connect(s_h, s_u, s_p, s_d)
if s_cn :
print "ok"
else:
print "no"
When I run this code it shows an unknown loaclhost error.
How can I fix it?
Have you added your ISP IP in remote mysql host access list? And enable port 3306 in your server firewall.
you choose wrong way to connect !!!
it's the code :
db = MySQLdb.connect(host="123.134.121.136",
port=3306,
user="xyz_alibaba",
passwd="!##!#1&#a##",
db="xyz_code")

Connecting to local SQL Server instance

I'm attempting to connect to a local instance of SQL Server running on my machine. I am able to connect to a local instance with this code from our server, but it fails on my local machine.
I've enabled named pipes and all the ips in the SQL Server configuration.
The code I'm using is as follows:
from pymssql import connect
server = r'.\SQLEXPRESS2014' # I've also tried MORGANT-PC\SQLEXPRESS and SQLEXPRESS2014
username = 'MyUserName'
password = 'MyPassword'
master_database_name = 'SuperSecretDatabase'
port = 5000
server_args = {'host': server, 'user': username, 'password': password,
'database': master_database_name, 'port': port} # I've tried having the first key be both host and server, because pymssql's docs are unclear on the difference.
master_database = connect(**server_args)
If I use the instance name, I get this error:
pymssql.InterfaceError: Connection to the database failed for an unknown reason.
I set the port to 5000 so that I could try connecting to it with
server = 127.0.0.1
port = 5000
which fails with the slightly different error message:
pymssql.OperationalError: (20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist\nNet-Lib error during Unknown error (10035)\n')
I've read a bunch of answers here on SO, and most of them seem to indicate it's an issue with FreeTDS, but I'm on Windows 8.1, so I don't have FreeTDS.
I've tried connecting with sqlcmd with the host\instance name and that works fine. It also works in SSMS.
I've tried passing .\SQLEXPRESS2014 to both the host and server parameter in pymssql.connect() and they both fail with the same aforementioned error.
I briefly tried using adodbapi, but I'm getting exactly the same error messages.
The solution ended up being a combination of things.
I needed to disable all IPs other than 127.0.0.1.
I needed to create C:\freetds.conf with the following text:
[global]
port = 1433
tds version = 7.0
I needed to change the account my SQL instance logs in with to LocalSystem.
Yes, 1433 s the default.
This works fine for me:
library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=server_name; Database=db_name;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(channel)
Try connecting on the default SQL server port, which is 1433, not 5000.
And check that you can connect to the correct instance using SQL mgmt studio.
I had a similar issue, with the following error:
_mssql.MSSQLDatabaseException: (18456, b"Login failed for user
'script_svc'.DB-Lib error message 20018, severity 14:\nGeneral SQL Server
error: Check messages from the SQL Server\nDB-Lib error message 20002,
severity 9:\nAdaptive Server connection failed\n")
The user I had established was a local user on the machine.
The solution for me was putting ".\" in front of the username and it then recognized it as a local user and allowed the query to work.
Your results may vary.. but I thought I would mention it.
Have you tried using pyodbc instead?
import pyodbc
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=SERVERNAME;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("select user_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
print row.user_id, row.user_name
Don't forget to add the ODBC driver to your Windows. Go to: Control Panel > Systems and Security > Administrative Tools > ODBC Data Sources
Either the 32-bit or 64-bit version depending on your computer.
Then you click on the System DNS file. If you do not see any MySQL driver you have to click ADD. It brings up a list, from that list select the MySQL driver.
For me, it was ODBC Driver 13 for SQL Server. Click finish. Once you do that then you have to change your connection line in your code to the corresponding Driver that you just filled out.
Source: pyodbc + MySQL + Windows: Data source name not found and no default driver specified

ssh first with mysqldb in python

I'm trying to connect to a MySQL database on a remote server using MySQLdb in python. The problem is that first I need to SSH into the host, and then from there, I need to connect to the MySQL server. The problem I'm having, though, is that MySQLdb does not seem to have a way of establishing an SSH connection before connecting to the SQL server. I've checked the documentation but have not had any luck.
This is how I'm connecting:
conn = MySQLdb.connect(host = 'mysqlhost.domain.com:3306', user = 'user', passwd = 'password', db = 'dbname')
But what I really need is something like this:
conn = MySQLdb.connect(sshhost = 'sshhost.domain.com', sshuser = 'sshusername', sshpasswd = 'sshpasswd', host = 'mysqlhost.domain.com:3306', user = 'user', passwd = 'password', db = 'dbname')
Which is of course just made up. Can anyone make any recommendations?
I prefer keeping the tunnel within the python code, I did hate to create tunnels manually, or separately, thanks to sshtunnel library its very simple to use.
Here is some simple sample that will work for what you want.
import MySQLdb
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
('sshhost.domain.com', 22),
ssh_password="sshpasswd",
ssh_username="sshusername",
remote_bind_address=('mysqlhost.domain.com', 3306)) as server:
conn = MySQLdb.connect(host='127.0.0.1',
port=server.local_bind_port,
user='user',
passwd='password',
db='dbname')
Setup an ssh tunnel before you use MySQLdb.connect. The tunnel will make it appear as though you have the mysql running locally, set it up something like this
ssh user#host.com -L 9990:localhost:3306
here your local port 9990 will bind to 3306 on the remote host, -L stands for local, then 9990:localhost:3306 means LOCALPORT:
conn = MySQLdb.connect(host = 'mysqlhost.domain.com:9990', user = 'user', passwd = 'password', db = 'dbname')
notice the 9990.
Add your public ssh key of user to the host.com so that you dont have to type the password each time you want to setup the tunnel (use public key authentication).
If you need to do this within python there is python-to-ssh binding libraries you could call from within python to setup the tunnel for you.

Categories

Resources