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)
Related
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?
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 using a Mac (OS 10.10.5), PyCharm, Python 3.5 and MySQL. MySQL has been working with PHP on the same machine. I'm trying to connect to it using Python and getting the error message:
enter code here2003: Can't connect to MySQL server on 'localhost::3306' (8 nodename nor servname provided, or not known)
Can someone list the diagnostic steps so I can correct the problem? Thanks, Doug
Below is the connection code:
import mysql.connector
from mysql.connector import errorcode
try:
cnn = mysql.connector.connect(
host="localhost:", # your host, usually localhost
user="root", # your username
password="root", # your password
database="bb_cards") # name of the data base
print("It Works!!")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with username or Password")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("Database Does not exist")
else:
print(e)
You have a colon where there shouldn't be one:
host="localhost:" # remove the : -> host="localhost"
127.0.0.1::3306 is not the same as 127.0.0.1:3306
There are somethings I make out from your code.
we can provide host="localhost" no semicolons. or we can provide a host/server value like 'host':'127.0.0.1:<port name>'
Check your port again to connect the database
We should always close the connection viz. cnn.close() when our task is complete.
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 am writing a module, in which the email string is validated before it gets inserted into the db. When i try to enter invalid email string it prints else block with wrong email message but when i enter the correct email string it doesnt do anything. Here is the code:
#!/usr/bin/python
import MySQLdb
import re
# Open database connection
db = MySQLdb.connect("localhost","root","root","acl" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
def addUser(email,password):
try:
if validateEmail(email):
sql = "INSERT INTO acl_users(email, password) VALUES ('%s', '%s')" % (email, password)
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
else:
print "wrong email"
except Exception as inst:
# Rollback in case there is any error
db.rollback()
print inst
def validateEmail(email):
if len(email) > 7:
if re.match("^.+\\#(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
return True
else:
return False
else:
return False
Any suggestions please?
edit-1
got the answer guys! after creating instance of the exception in except block i got to know that import re was missing. that solved the problem.
in validateEmail you use the module re, but you did not import it.
I would print out the exception and see why it's failing.
Is it possible that an exception is thrown in the if block? Put a print statement in the except block to check for that.
Also it's usually a bad idea to have a catch-all except block. If you're anticipating database errors then have a except block that catches them.