python - 为什么 MySQL 会执行返回 None?

标签 python mysql sql

我正在尝试使用 Python 的 (3.4) MySQL 模块和以下代码查询本地 MySQL 数据库:

class databases():

  def externaldatabase(self):

  try:
    c = mysql.connector.connect(host="127.0.0.1", user="user",
                                password="password", database="database")
     if c.is_connected():
           c.autocommit = True
      return(c)
    except:
         return(None)
    d = databases().externaldatabase()
    c = d.cursor() 
    r = c.execute('''select * from tbl_wiki''')
    print(r) 
> Returns: None

据我所知,连接成功,数据库由几行组成,但查询总是返回无类型。

MySQL执行函数返回None的实例有哪些?

最佳答案

查询执行没有返回值。

您需要遵循的模式是:

cursor creation;
cursor, execute query;
cursor, *fetch rows*;

或者在 python 中:

c = d.cursor()

c.execute(query)    # selected rows stored in cursor memory

rows = c.fetchall()    # get all selected rows, as Barmar mentioned
for r in rows:
    print(r)

还有一些数据库模块允许您使用 for...in 模式遍历游标,但对 mysql 进行三重检查。

关于python - 为什么 MySQL 会执行返回 None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421466/

相关文章:

python - 字段名称 `username` 对模型无效

php - 在 MySQL 中将日期转换为 Unix 时间戳会出现错误 LIMIT 0、25

javascript - 如何将sql添加到javaScript函数中?

sql - RETURN 在带有 TRY-CATCH block 的事务内

python - 如何使用python单击窗口的 'next'按钮

python - 三元返回/赋值与传统 if-else block 的比较

python - 在 Python 多处理中使用 __name__= ='__main__' 的解决方法

php - 当文件从本地主机移动到服务器时,登录表单不起作用

mysql - SQL 我的子查询永远加载

MySQL 查询 LocalDateTime 字段上的 DATE() 函数