could you advise me on best practices on how to deal with MySQL class in Python application?
class DBClient:
def __init__(self, db_name=None):
self.conn = None
self.db_name = db_name
self.__create_connection()
def __create_connection(self):
try:
self.conn = mysql.connector.connect(
host="127.0.0.1",
port=3306,
user="root",
password="password",
database=self.db_name
)
print('DB Connection successful')
except InterfaceError as e:
exit(e)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
def __del__(self):
if self.conn:
self.conn.close()
def __commit(self):
self.conn.commit()
DBClient(config.DB_NAME).create_items_table()
in general the problem is:
as you noticed the method __create_connestion specified to which database we would like to connect. The problem is if the the database is not created. How to avoid code duplication in that scenario:
connect to DB
if db is not created -> create that
if db is created -> connect
It is not a good idea to create a database automatically, it is an action that is better to do yourself.
Never put credentials in code, use environment variables instead, please have a look at this module
Dotenv
so if I understand correctly it is better to have sth like this in main:
if __name__ == '__main__':
DBClient(config.DB_NAME).to_do_something()
and have separate script, lets say setup_db.py which is going to create a database and schema?
Related
I'm writing some Python code to connect to our Snowflake Database and getting an error in my Python (I'm new to Python so i've likely done something wrong here).
I'm getting <class 'NameError'> TestConnection.py 98 inside my script, which has the relevant parts below
def connection(obj):
try:
global cur, engine
cur = obj.cursor_connection().cursor()
engine = obj.engine_connection().engine.connect()
except Exception as e:
print(e)
sql = "select current_warehouse(), current_database(), current_schema();"
try:
print("Cursor connection successful")
except Exception as e:
print(e)
try:
print("Engine connection successful")
except Exception as e:
print(e)
return cur, engine
try:
#Setup Connection with both cursor and the engine
db, schema= login.db, login.schema
obj = connect(db, schema)
cur , engine = connection(obj)
The line I'm getting the error on is the cur,engine = connection(obj) part.
I had a previous error before (UnboundLocalError) but putting global cur, engine inside the connection function fixed that, but getting NameError now.
What am I doing wrong here?
Thanks
try this
import snowflake.connector
ctx = snowflake.connector.connect(
user='<user_name>',
password='<password>',
account='<account_identifier>'
)
cs = ctx.cursor()
Ok, I've fixed this now, it was indentation on the functions and class.
I ended up with
class connect:
def __init__
def cursor_connection
def engine_connection
def connection
and that has it working whereas having def_connection tabbed in was breaking it.
So I am having a super hard time connecting to a local database using the python mysql.connector module.
So I am trying to connect using the highlighted connection. I use the password abcdefghijkl to log into the SQL environment. I am trying to connect to a database named flight_school.
My python script looks like so.
import mysql.connector
mydb = mysql.connector.connect("localhost", "root", "abcdefghijkl", "flight_school")
print(mydb.is_connected())
This above code in the arguments in the following order i.e.
hostname = localhost,
user = 'root',
password = 'abcdefghijkl', and
database name = 'flight_school'.
It's just not working. I get the following error.
I would really appreciate some advice, please.
Please read always the official documentation
Your cooenction stirng has to have this form(if you do it this way=
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="testpaaword",
database="testdb"
)
Check out SQL-Alchemy module, works wonders from my experience.
Please read always the official documentation: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
import mysql.connector
from mysql.connector import errorcode, MySQLConnection
try:
db_connection = MySQLConnection(user='root', password='', port='3306', database='your_database')
print("Database connection made!")
except mysql.connector.Error as error:
if error.errno == errorcode.ER_BAD_DB_ERROR:
print("Database doesn't exist")
elif error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("User name or password is wrong")
else:
print(error)
else:
db_connection.close()
cursor = db_connection.cursor()
sql = ("commands")
cursor.execute(sql)
I'm trying to automate (by using python scripting) the ability to create a MySQL role, but for some reason I am unable to put my string variable into mysql command. This is what I've got so far:
#!/usr/bin/python3
import mysql.connector
from mysql.connector import errorcode
# Open database connection
try:
serverHostName='localhost'
userName='root'
passwd='password'
databaseName='mysql'
roleName='reader'
cnx = mysql.connector.connect(
host=serverHostName,
database=databaseName,
user=userName,
password=passwd)
cursor=cnx.cursor(prepared=True)
dropRole="""DROP ROLE IF EXISTS %s """
print(dropRole, roleName)
#cursor.execute(dropRole, roleName)
#cnx.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
print("You have successfully disconnected from your MySQL database")
what comes out is the following:
DROP ROLE IF EXISTS %s reader
You have successfully disconnected from your MySQL database
If anyone can explain to me why %s and the reader is showing up in my print line that would be much appreciated.
You didn't call a formatting operator to subsitute roleName into the string, so it's just printing the format string. Use the % operator to perform formatting.
print(dropRole % roleName)
there’s something wrong in my python script: when I try to put some data in my database and print it, it looks like it’s working, but when I rerun the code, or if I check the phpmyadmin, there’s no data saved in the db. Does anyone have some idea on how to solve this problem?
import mysql.connector
from mysql.connector import errorcode
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='Temperature',
user='Temperature',
password='mypass')
if conn.is_connected():
print('Connected to MySQL database')
cur = conn.cursor()
query = "INSERT INTO Temp(temp, humi) " \
"VALUES(315, 55)"
try:
cur.execute(query)
except MySQLdb.ProgrammingError as e:
print(e)
query = "SELECT * FROM Temp"
try:
cur.execute(query)
for reading in cur.fetchall():
print (str(reading[0])+" "+str(reading[1]))
except MySQLdb.ProgrammingError as e:
print(e)
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
You will need to add conn.commit() before conn.close(). That should solve the problem.
I'm newbie in Python. I'm trying to use Python to connect MySQL Server. I wrote like guides from MySQL official page, it was OK. But, when I create a connector class, it raised the error "MySQL Connection not available"
Here is my class
import mysql.connector
from mysql.connector import errorcode
## BEGIN MySQL Connector Class
class MySQLConnector :
configs = {
"user":"root",
"password":"",
"host":"127.0.0.1",
"database":"python_db",
"raise_on_warnings": True
}
cursor = None
connection = None
## BEGIN Constructor
def __init__(self, configs = {}) :
if(any(configs)!=False) :
self.configs = configs
## END Constructor
## BEGIN Open
def open(self) :
try:
self.connection = mysql.connector.connect(self.configs)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
finally:
self.connection.close()
return self.connection
## END Open
## BEGIN close connection
def close(self) :
self.cursor.close()
self.connection.close()
## END close connection
## BEGIN execute
def execute(self, query) :
if(self.connection == None) :
print("Connection is None")
return
self.cursor = self.connection.cursor()
if(self.cursor!=None) :
self.cursor.execute(query)
else:
print("Cursor is 'None'")
## END execute
## END MySQL Connector Class
## BEGIN RUN
objConnect = MySQLConnector()
objConnect.open()
objConnect.execute("SELECT * FROM User")
Please show me the way to solution and explained me why my code has error.
Thanks!
EDITED
Finally, mata and alecxe help me to solve this problem, I don't know which solution to be choosen. I summary here for someone has mistake like me:
1. Remove the finally statement.
2. Using ** in self.connection = mysql.connector.connect(**self.configs)
Even if you correct the error alecxe pointed out, your code still won't work.
The finally block ensures that each connection is closed before it is returned, no matter wheather there was an exception or not, so the open method only returns closed connections.
You are passing a dictionary object self.configs into mysql.connector.connect, though, according to docs, you should pass to it user, password and other arguments. Looks like you need to unpack configs:
self.connection = mysql.connector.connect(**self.configs)
Hope this is it.