2017-03-24 81 views
-2

我在python程序中有這樣的查詢:如何從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() 
+1

讓我們來看看你有什麼代碼,所以我們可以幫助你得到的結果。 – karthikr

+0

究竟是什麼? –

+0

看起來像[pandas](http://pandas.pydata.org/)是當你執行'results = cursor.fetchall()'時你需要的 – Copperfield

回答

-1

不優雅,但它可以幫助解開這個神祕的Python接口Cursor類和元組(見科波菲爾評論)與查詢,數據列表傳輸到一個列表(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() 
+0

'sql =(「INSERT INTO phonebook(name,phone,city)VALUES(''+ name +'','」+ detail ['phone'] +「','」+ ['city'] +'')「。format(table))'是一個等待發生的事故,[Bobby Tables的小媽媽會說](https://xkcd.com/327/)。切勿將值連接或格式化爲SQL查詢。 [始終使用佔位符](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html)。 –

+0

無法與媽媽爭論 - sql =(「INSERT INTO {}(name,phone,city)VALUES('{}','{}','{}')」。format(table,name,detail [ 'phone'],詳細['city'])) Howzat? – user222216

+0

「或格式」。請閱讀[SQL注入](https://en.m.wikipedia.org/wiki/SQL_injection)和緩解措施,尤其是參數化查詢。訣竅是在查詢中使用佔位符,即* DB-API驅動程序*從傳入的值中填充。 –

相關問題