Flask error when connecting to mysql using pymysql - python

So I am using pymysql to conenct mysql to flask. When I was developing a website on my local computer everything was fine, later when I uploaded my website to digital ocean trying to connect gives me an error:
'NoneType' object is not iterable
The view I get the error in:
#app.route('/test/')
def test_page():
try:
c, conn = connection()
return("okay")
except Exception as e:
return(str(e))
The connection file looks like this:
import pymysql
def connection():
try:
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="my_password",db="db_name",charset='utf8')
c = conn.cursor()
return conn, c
except Exception as e:
print (str(e))
I am stuck with this problem for like couple of hours, cant find a solution. Thank you in advance.

Your pymysql.connection is trying to connect to a database running on the local machine.
Evidently there is no database on your Digital Ocean server, or if there is it's not accessible on port 3306 with the credentials provided.

Found a mistake. All I need was a fresh reinstall of mysql :)

Related

Connecting to PostgreSQL on Google Cloud Platform using Unix Sockets and SQLAlchemy

I am trying to connect to a PostgreSQL database hosted on a Google Cloud Platform instance using unix sockets and the SQLAlchemy library. My database instance is configured to accept unix socket connections.
When I run my application locally, I use the following line to connect to the database and it works perfectly:
pool = create_engine("postgresql://{user}:{password}#/{dbname}?host={socket}".format(params_dic))
However, when I run the same application on Google Cloud Platform, I get an error with the following connection string:
pool = create_engine(engine.url.URL.create(
drivername="postgresql+psycopg2",
username=params_dic['user'],
password=params_dic['password'],
database=params_dic['dbname'],
query={"unix_socket": "{}/.s.PGSQL.5432".format(params_dic['socket'])},
),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=100,)
The error message is: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "unix_socket"
How can I connect to a PostgreSQL database on Google Cloud Platform using unix sockets and SQLAlchemy?
I Tried connecting to GCP Postgres with unix socket and SQLAlchemy, expected success but got error "invalid dsn: invalid connection option "unix_socket"
Also I dont want to use a Public IP conection.
I was able to solve it using the psycopg2 library directly, there was also a missing line in the .yaml file to add the instance to the uinx socket. Thank you all.
de function:
def connect(params_dic):
"""
Generate the connection to the database
"""
if is_gcp():
print('coneccting from GCP...')
conn = None
try:
conn = ppg2.connect(
host=params_dic['socket_dir']+'/'+params_dic['socket'],
database = params_dic['dbname'],
user = params_dic['user'],
password = params_dic['password'],
)
return conn
except Exception as error:
print('problema en la funcion ppg2: ',error)
else:
print("Running locally")
conn = None
try:
# connect to the PostgreSQL server
conn = ppg2.connect(**params_dic)
except (Exception, ppg2.DatabaseError) as error:
print(error)
return conn
the missing line in the yaml file
beta_settings:
cloud_sql_instances: proyect-name:region:instance-name

remotemysql.com cannot connect with python neither on the site manually

I try to reach to my remotemysql database with my Python script which worked fine first, now it doesn't connect anymore so I went to remotemysql.com/login.php but it gives an error
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
anyone know if its only for me or if remotemysql.com is having problems?
my code for Python should also be fine.
these are random credentials in my code btw.
try:
conn = mysql.connector.connect(
host='remotemysql.com',
database='thydfc2',
user='thydfc2',
password=os.environ.get('databasepass'))
except Error as e:
print(e)
if conn.is_connected():
mycursor = conn.cursor()```

How to share a mysql connection that is inside a function?

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)

Connect to postgresql using python script (database URI) but detects 'conn' as string

I am using a simple python script to connect the postgresql and future will create the table into the postgresql just using the script.
My code is:
try:
conn = "postgresql://postgres:<password>#localhost:5432/<database_name>"
print('connected')
except:
print('not connected')
conn.close()
when I run python connect.py (my file name), it throws this error :
Instance of 'str' has no 'commit' member
pretty sure is because it detects 'conn' as a string instead of database connection. I've followed this documentation (33.1.1.2) but now sure if Im doing it right. How to correct this code so it will connect the script to my postgresql server instead of just detects it as a string?
p/s: Im quite new to this.
You are trying to call a method on a string object.
Instead you should establish a connection to your db at first.
I don't know a driver which allows the use of a full connection string but you can use psycopg2 which is a common python driver for PostgreSQL.
After installing psycopg2 you can do the following to establish a connection and request your database
import psycopg2
try:
connection = psycopg2.connect(user = "yourUser",
password = "yourPassword",
host = "serverHost",
port = "serverPort",
database = "databaseName")
cursor = connection.cursor()
except (Exception, psycopg2.Error) as error :
print ("Error while connecting", error)
finally:
if(connection):
cursor.close()
connection.close()
You can follow this tutorial

Error when connecting to MySQL database with Python

I am using a simple python function to connect to a MySQL database.I receive an error saying a variable is referenced before it is assigned, but this would not be the case if the connection had successfully established. Why is the connection failing?
I am using Ubuntu Linux 18.04. I am running xampp 7.3 to host the mySQL and apache servers and am using phpmyadmin to access the database.I am running my code with python 3.
This is my code:
import mysql.connector
from mysql.connector import Error
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='myDB',
user='xxx',
password='yyy!')
if conn.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
And this is the error I receive:
Traceback (most recent call last):
File "01_python-mysql-connect.py", line 23, in <module>
connect()
File "01_python-mysql-connect.py", line 19, in connect
conn.close()
UnboundLocalError: local variable 'conn' referenced before assignment
I am expecting a successful connection to the database. I believe something could be wrong with my configurations but don't know where to start in solving the problem. Thank you.
This line
conn = mysql.connector.connect(host='localhost',
database='myDB',
user='xxx',
password='yyy!')
is failing. So conn never gets a value assigned to it. But you have a try...except...finally block and in the finally clause your code is doing conn.close(). But conn hasn't been assigned because the statement that was supposed to assign it a value failed. That is why you are seeing the message local variable 'conn' referenced before assignment. To discover what is wrong, move the call to close out of the finally clause and put it before the except. You can always move it back later.
If the mysql.connector.connect() call fails, conn will not be assigned, hence the "referenced before assignment" exception.
This is an ideal use case for the contextlib.closing context manager, I think. Try something like this:
from contextlib import closing
try:
with closing(mysql.connector.connect(...)) as conn:
if conn.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
This will cleanly and reliably take care of closing your connection for you.

Categories