【问题标题】:How to get columns from a query in python?如何从python中的查询中获取列?
【发布时间】:2017-08-17 14:38:22
【问题描述】:

我在 python 程序中有该查询:

我应该为查询中的每一列创建一个多维数组(如果可能的话)或从这个查询中创建四个数组。

你能提出一个优雅的方法来解决它吗?

conn = #connection to the server
cursor=conn.cursor()
query = (" select id, name, phone, city from guest")

cursor.execute(query)
results = cursor.fetchall
for i in results:
     print i
cursor.close()
conn.close()

【问题讨论】:

  • 让我们看看你有什么代码,所以我们可以帮助你得到结果。
  • 究竟是什么的查询?
  • 看起来 pandas 是你所需要的
  • 当您执行results = cursor.fetchall() 时,result 已经是包含查询数据(或多维数组)的元组列表,如果您想要特定列,请在查询中请求,或从结果中提取它
  • 可以查看sqlite3文档中的示例

标签: python mysql-python


【解决方案1】:

不优雅,但它可能有助于解开神秘的 Python 连接器游标类,并将元组列表(参见 Copperfield 评论)与查询中的数据一起传输到字典(条目)列表(phoneList)中,其中包含每个字典(条目)的详细信息数据库中的条目,这可能更容易在您的 python 脚本中使用:

# ref: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html
import mysql.connector

db = 'test'
table = 'phonebook'
phoneList = []

drop_table   = ("DROP TABLE IF EXISTS {};").format(table)
# By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
# To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
# ALTER TABLE phonebook AUTO_INCREMENT=100;
create_table = ("CREATE TABLE {} ("
            "id int NOT NULL AUTO_INCREMENT,"
            "name varchar(30) NOT NULL,"
            "phone varchar(30) NOT NULL,"
            "city  varchar(30) NOT NULL,"
            "PRIMARY KEY (id))"
            " ENGINE=InnoDB DEFAULT CHARSET=latin1;").format(table)

Names = {'Bill':{'phone':'55123123','city':'Melbourne'},
     'Mary':{'phone':'77111123','city':'Sydney'},
     'Sue':{'phone':'55888123','city':'Melbourne'},
     'Harry':{'phone':'77777123','city':'Sydney'},
     'Fred':{'phone':'88123444','city':'Yongala'},
     'Peter':{'phone':'55999123','city':'Melbourne'}}


cnx = mysql.connector.connect(user='mysqluser', password='xxxx',host='127.0.0.1',database=db)
cursor = cnx.cursor(dictionary=True)  # key to using **row format
cursor.execute(drop_table)
cursor.execute(create_table)
# populate db
for name,detail in dict.items(Names):
    sql = ("INSERT INTO {} (name,phone,city) VALUES ('{}','{}','{}')".format(table,name,detail['phone'],detail['city']))
    cursor.execute(sql)

sql = ("SELECT id,name,phone,city FROM {}".format(table))
cursor.execute(sql)

for row in cursor:
    print("{id} {name} {phone} {city}".format(**row))
    phoneList.append(row)

print phoneList[0]['name'],phoneList[0]['city']
print phoneList[3]['name'],phoneList[3]['phone']


for entries in phoneList: # list of dictionaries
    print entries['name'],entries

for entries in phoneList:
    for k,v in dict.items(entries):
        print k,v
    print "\n"

cnx.close()

【讨论】:

  • sql = ("INSERT INTO phonebook (name,phone,city) VALUES ('"+name+"','"+detail['phone']+"','"+detail['city']+"')".format(table)) 是一场等待发生的意外,mom of little Bobby Tables would say。切勿将值连接或格式化到 SQL 查询。 Always use placeholders.
  • 不能和妈妈争论 - sql = ("INSERT INTO {} (name,phone,city) VALUES ('{}','{}','{}')".format (table,name,detail['phone'],detail['city'])) Howzat?
  • “或格式”。请阅读SQL injection 和缓解措施,尤其是参数化查询。诀窍是在查询中使用占位符,DB-API 驱动程序 从传递的值中填充。
  • 感谢您的链接,我看看这是否用于接受来自网页的用户输入,它可能会破坏您的数据库,因此应避免这种做法。我的示例避免了注入,因为它在没有用户输入的情况下填充数据库,只是为了提供数据作为工具来演示从 @Daniel 的游标类创建多维数组。 W3schools SQL Injection 这个主题的另一个很好的链接。
  • 如果像“O'Malley”这样的名字恰好出现在初始数据中。不幸的是,无法将标识符作为参数(表名等)传递,因此在您的示例中这是不可避免的,但通常标识符不是用户控制的。 MySQL 连接器使用百分比占位符,因此正确的方法是sql = "INSERT INTO {} (name,phone,city) VALUES (%s, %s, %s)".format(table),然后是cursor.execute(sql, (name,detail['phone'],detail['city']))。请注意,这些是 not Python 的旧样式字符串格式化占位符,虽然相似,所以 sql % (...) not 被使用。
猜你喜欢
  • 2015-10-15
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
相关资源
最近更新 更多