只是把以前的评论和reorganicing: 目前代码:
import MySQLdb
serv = MySQLdb.connect(host = "localhost", user = "root", passwd = "abcdefg")
c = serv.cursor()
print c.execute("SHOW DATABASES")
随着建议的修改:
import MySQLdb
serv = MySQLdb.connect(host = "localhost", user = "root", passwd = "abcdefg")
c = serv.cursor()
c.execute("SHOW DATABASES")
l = c.fetchall()
print l
l = [ i[0] for i in l ]
print l
在我的情况下输出看起来象(这是所需的输出):
(('information_schema',), ('data',), ('mysql',), ('performance_schema',), ('sys',))
['information_schema', 'data', 'mysql', 'performance_schema', 'sys']
请注意以下常见的错误,以避免错误:如果您尝试c.execute("SHOW DATABASES").fetchall()
你将有一个错误:AttributeError: 'int' object has no attribute 'fetchall'
。这就是你应该首先编写c.execute("SHOW DATABASES")
,其次编写c.fetchall()
。
@执行''后执行'print c.fetchall()'# – khelwood
@khelwood:非常好,谢谢!我显然是这样的一个小菜鸟。还添加了'l = c.fetchall(); l = [i [l] for i in l]'因为它返回的元组元组元组的元组元组中的第二个元素为null - 你知道这是为什么吗? – pshep123
[相关](https://stackoverflow.com/questions/14551009/mysqldb-cursors-cursor-execute-returns-different-values-in-case-of-different-cur):execute返回行中的行数导致你的上下文。 – agtoever