python - 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
解决方案
你可以像这样得到它:
db.query('SELECT CURRENT_USER();')
r = db.store_result()
r = r.fetch_row()
print(r[0][0])
推荐阅读
- java - 如何从firebase读取子数据
- hadoop - Sqoop:如何从 hive 联合导出表
- sql-server - 无法连接到具有多个 SQL 实例的服务器上的 SQL SERVER 实例
- javascript - 我不知道为什么这个 Javascript 只覆盖了一半的屏幕
- flutter - 如何保留列表视图项?
- javascript - Javascript/Node JS,下载文件时如何检查文件大小并下载文件的第一个千字节
- flutter - 测量颤振应用程序启动时间
- html - CSS 元素没有响应
- oracle - 如何在 sql*plus 中使用 dbms_lob.substr
- javascript - 在 Altair / Vega 中,有没有办法在点击时运行任意 Javascript 代码?