从已建立的 mysql 连接中获取用户
get user from established mysql connection
我已经使用 MySQLdb
python 库建立了 MySQL 连接。由于初始连接发生在完全不同的地方,我想从给定的 MySQLdb.connections.Connection
对象中获取用户名。
经过对源代码的一些研究和一些测试,我没有找到任何获取用户名的方法。
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)
输出:
AttributeError: 'Connection' object has no attribute 'user'
有什么办法可以得到这种属性吗?
版本:
MySQL分贝:1.4.2.post1
Python: 2.7
你可以这样获取:
db.query('SELECT CURRENT_USER();')
r = db.store_result()
r = r.fetch_row()
print(r[0][0])
错误消息说明了一切。
AttributeError: 'Connection' object has no attribute 'user'
您可以通过执行这段代码来验证这一点:
from MySQLdb import Connection
x = dir(Connection)
print(x)
它将打印 Connection
对象的属性。输出如下所示:
['__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__']
因此,没有 user
属性。
为了获得当前用户,您可以按照@Tamoor Salah-U-Din 的建议进行操作。
希望对您有所帮助
我已经使用 MySQLdb
python 库建立了 MySQL 连接。由于初始连接发生在完全不同的地方,我想从给定的 MySQLdb.connections.Connection
对象中获取用户名。
经过对源代码的一些研究和一些测试,我没有找到任何获取用户名的方法。
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)
输出:
AttributeError: 'Connection' object has no attribute 'user'
有什么办法可以得到这种属性吗?
版本:
MySQL分贝:1.4.2.post1
Python: 2.7
你可以这样获取:
db.query('SELECT CURRENT_USER();')
r = db.store_result()
r = r.fetch_row()
print(r[0][0])
错误消息说明了一切。
AttributeError: 'Connection' object has no attribute 'user'
您可以通过执行这段代码来验证这一点:
from MySQLdb import Connection
x = dir(Connection)
print(x)
它将打印 Connection
对象的属性。输出如下所示:
['__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__']
因此,没有 user
属性。
为了获得当前用户,您可以按照@Tamoor Salah-U-Din 的建议进行操作。 希望对您有所帮助