Values not being defined when outputted in Python MySQL?

◇◆丶佛笑我妖孽 提交于 2021-01-07 02:35:08

问题


Aided by a previously asked question see (How to correctly convert SQL rows to columns?), I'm attempting to apply to a MySQL connector script written in python. As seen by @Popeye 's fiddle http://sqlfiddle.com/#!9/997790/25, my attempt at returning all rows now with a null value for Person C but its output is seen below

import mysql.connector

db = mysql.connector.connect(
     host="localhost",
     port="3307",
     user="root",
     passwd="#",
     database="#"
  )
mycursor = db.cursor()
mycursor.execute("CREATE TABLE trial157 (Name TEXT(13) NULL , A1 TEXT(13) NULL ,  A2 TEXT(13) NULL ,  A3 TEXT(13) NULL ,  A4 TEXT(13) NULL)")


sql = "INSERT INTO trial157(Name, A1, A2, A3, A4) VALUES (%s, %s, %s, %s, %s)"
val = [
  ('Person A', 'C', 'T', 'R', 'S'),
  ('Person B', 'M', 'V', 'R', 'S'),
  ('Person C', 'M', None , 'R', 'C')
]
mycursor.executemany(sql, val)
db.commit()


mycursor.execute("SELECT * From (select name_new, max(case when name = 'PersonA' then A end) as PersonA, max(case when name = 'PersonB' then A end) as PersonB, max(case when name = 'PersonC' then A end) as PersonC from (select name, 'A1' name_new, A1 A from trial157 union all select name, 'A2' name_new, A2 A from trial157 union all select name, 'A3' name_new, A3 A from trial157 union all select name, 'A4' name_new, A4 A from trial157 ) t group by name_new) t where PersonC is null")
myresult = mycursor.fetchall()
for x in myresult:
  print(x)
 - OUTPUT
('A1', None, None, None)                                                                                     
('A2', None, None, None)
('A3', None, None, None)
('A4', None, None, None)
[Finished in 1.2s]

回答1:


You have used wrong names.(in case expression names are used without space. You should use it exactly same as per val)

Replace

max(case when name = 'PersonA' then A end) as PersonA

With

max(case when name = 'Person A' then A end) as PersonA

See the space between Person and A in name. Do the same for Person B and Person C



来源:https://stackoverflow.com/questions/65507118/values-not-being-defined-when-outputted-in-python-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!