I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.
Related
I am a beginner in python and mysql. I have a small application written in Python that connects to remote mysql server. There is no issues to connect and fetch data. It works fine then the code is outside a function. As I want to close and open connections, execute different queries from several functions inside my application, I would like to be able to call a function to establish a connection or run a query as needed. It seems that when I create an connection, that connection can not be used outside the function. I would like to implement something like this:
mydbConnection():
....
mydbQuery():
....
connected = mydbConnection()
myslq = 'SELECT *.......'
result = mydbQuery(mysql)
And so on...
Thanks for any direction on this.
import mysql.connector
from mysql.connector import Error
def mydbConnection(host_name, user_name, user_password):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
connection = mydbConnection("localhost", "root", "")
In the above script, you define a function mydbConnection() that accepts three parameters:
host_name
user_name
user_password
The mysql.connector Python SQL module contains a method .connect() that you use in line 7 to connect to a MySQL database server. Once the connection is established, the connection object is returned to the calling function. Finally, in line 18 you call mydbConnection() with the host name, username, and password.
Now, to use this connect variable, here is a function:
def mydbQuery(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
To execute queries, you use the cursor object. The query to be executed is passed to cursor.execute() in string format.
Create a database named db for your social media app in the MySQL database server:
create_database_query = "CREATE DATABASE db"
mydbQuery(connection, create_database_query)
I am using mysql.connector to connect to a mysql DB, while i can connect manually to the db using sql server management, if i try connecting via code, it returns this error after awhile :
mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at 'host:1234', system error: 10054 An existing connection was forcibly closed by the remote host
These are the connection details :
connection = mysql.connector.connect(host='host',
port = '1234',
database='DBname',
user='Usr',
password='pwd')
If I create a local mysql DB, the connection works just fine.
I assume some security stuff is going on, anyone else had encountered this situation ? Anything that I'm doing wrong? Should I add anything to the connection.connect input ?
Full code for reference :
import mysql.connector
from mysql.connector import Error
connection = mysql.connector.connect(host='host',
port = '1234',
database='DBname',
user='Usr',
password='pwd')
sql_select_Query = "select * from TableName"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
print("Total numb of rows selected is : ", cursor.rowcount)
print("\nPrinting each row")
for row in records:
print(row)
connection.close()
I'm learning Python and attempting a tutorial to connect to a remote database.
The problem that I'm having is that I'm not sure what to replace localhost with, I've tried domains, IP address etc. but keep getting the following error.
OperationalError: (2003, "Can't connect to MySQL server on 'remotehost
name' (timed out)")
# Open database connection
db = pymysql.connect("localhost","username","password","dbname" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS rsstracker")
# Create table as per requirement
sql = """CREATE TABLE rsstracker (
article_title varchar(255),
article_url varchar(1000),
article_summary varchar(1000)
summary )"""
cursor.execute(sql)
# disconnect from server
db.close()
You should replace localhost with the server's IP address or host name. If that server is in your LAN you will need its internal address. If it is outside your network you will need its external address.
Either way you will need to make sure the port you are using is well forwarded and not blocked/filtered by routers / firewalls along the way, including on / by the remote server's operating system.
This question may be more appropriate on superuser exchange.
I'm trying to create a postgres DB using a python script. Some research showed that using the psycopg2 module might be a way to do it. I installed it and made the required changes in the pg_hba.conf file. I used the following code to create the DB:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from psycopg2 import connect
import sys
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
con = None
con = connect(user='****', host = 'localhost', password='****')
dbname = "voylla_production1710"
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute('CREATE DATABASE ' + dbname)
cur.close()
con.close()
I tried replacing con = connect(user='nishant', host = 'localhost', password='everything') with con = connect(user='nishant', password='everything')
But I'm getting the following Error:
con = connect(user='nishant', host = 'localhost', password='everything')
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL: database "nishant" does not exist
Could someone please tell me the right way of doing it.
Thanks
PostgreSQL's client connects to a database named after the user by default.
This is why you get the error FATAL: database "nishant" does not exist.
You can connect to the default system database postgres and then issue your query to create the new database.
con = connect(dbname='postgres', user='nishant', host='localhost', password='everything')
Make sure your nishant user has permission to create databases.
Edit: By the way, check out the ~/.pgpass file to store password securely and not in the source code (http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html). libpq, the postgresql client librairy, check for this file to get proper login information. It's very very handy.
I am unable to connected to database in linux using psycopg2. I have postgresql installed in linux and my code is:
import psycopg2
def testEgg():
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
cur = conn.cursor()
cur.execute("CREATE TABLE egg ( num integer, data varchar);")
cur.execute("INSERT INTO egg values ( 1, 'A');")
conn.commit()
cur.execute("SELECT num from egg;")
row = cur.fetchone()
print row
cur.close()
conn.close()
testEgg()
And the I got the error:
psycopg2.OperationalError: FATAL: Ident authentication failed for user "postgres"
This code runs well in windows7 but got above mentioned error in linux.
Is there anything I need to do more in linux? Any suggestion will be appreciated.
Thank you.
It's not a problem due to your code, but due to the permission of the postgres user.
You should create a new user to access to your database and replace this :
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
by (replace <your_user> by your real user name ...)
conn = psycopg2.connect("dbname = myDatabase user = <your_user> port = 5432")
To create a new user on postgres, you can use the 'createuser' binary. The documentation is available here.