Reputation: 1257
I have established an MySQL connection using MySQLdb
python library. Due to the fact that initial connection is taking place in totally different place I would like to get the username from a given MySQLdb.connections.Connection
object.
After some study of source code and some tests I didn't find any way to get the username.
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=dbname,
use_unicode=True,
charset="utf8mb4",
cursorclass=MySQLdb.cursors.DictCursor
)
try:
print(db.user)
except Exception as e:
print(e)
Output:
AttributeError: 'Connection' object has no attribute 'user'
Is there any way to get this kind of attribute?
Versions:
MySQLdb: 1.4.2.post1
Python: 2.7
Upvotes: 0
Views: 263
Reputation: 922
The error message says it all.
AttributeError: 'Connection' object has no attribute 'user'
You can verify this by executing this piece of code:
from MySQLdb import Connection
x = dir(Connection)
print(x)
It will print the attributes of the Connection
object. The output looks like this:
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Therefore, there is not a user
attribute.
In order to get the current user you can do what @Tamoor Salah-U-Din suggested. I hope this helps
Upvotes: 0
Reputation: 350
You can get it like this:
db.query('SELECT CURRENT_USER();')
r = db.store_result()
r = r.fetch_row()
print(r[0][0])
Upvotes: 1