首页 > 解决方案 > get user from established mysql connection

问题描述

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

标签: pythonmysql-python

解决方案


你可以像这样得到它:

db.query('SELECT CURRENT_USER();')
r = db.store_result()
r = r.fetch_row()
print(r[0][0])

推荐阅读