2012-07-19 18 views
4

我想在MySQL中取數組。有人可以告訴我如何使用MySQLdb來使用Python嗎?Python MySQL取數組

例如,這是我想什麼在Python做:

<?php 

    require_once('Config.php'); 

    $q = mysql_query("SELECT * FROM users WHERE firstname = 'namehere'"); 
    $data = mysql_fetch_array($q); 
    echo $data['lastname']; 

?> 

感謝。

回答

4
  1. 安裝MySQLdb(用於Python的MySQL的驅動程序)。類型pip install mysql-python
  2. 請閱讀Python DB API,這是訪問Python中數據庫的標準方式。

那麼,試試這個:

>>> import MySQLdb 
>>> connection = MySQLdb.connect(database='test') 
>>> cursor = connection.cursor() 
>>> cursor.execute('SELECT * FROM users WHERE firstname = %s',('somename',)) 
>>> results = cursor.fetchall() 
>>> for i in results: 
     print i 
+2

令人擔憂的是,這是SQL轉義的某種形式的唯一答案。 – tadman 2012-07-19 18:36:07

+0

謝謝你的幫助!我還有一個問題。當我使用它時,數據以這種格式返回:(('dave',),('jake',))。我如何編輯這些數據的格式,所以它就像這樣('dave','jake')。我正在循環返回的數據並將每個數據用作變量。這對我的目的來說更容易操作。再次感謝。 – 2012-07-21 04:43:01

+9

'names = [i [0] for my in cursor.fetchall()]' – 2012-07-21 04:50:20

1

我會用SQLAlchemy。這樣的事情會做的伎倆:

 
engine = create_engine('mysql://username:[email protected]:port/database') 
connection = engine.connect() 
result = connection.execute("select username from users") 
for row in result: 
    print "username:", row['username'] 
connection.close() 

0

嘗試:

import MySQLdb 
connection = MySQLdb.connect(host="localhost", # your host 
        user="root", # username 
        passwd="password", # password 
        db="frateData") # name of the database) 
cursor = connection.cursor(MySQLdb.cursors.DictCursor) 
cursor.execute('SELECT * FROM users WHERE firstname = %s',['namehere']) 
data = cursor.fetchall() 
print data['lastname'] 

請注意,在通過下面的參數啓動你的光標:「MySQLdb.cursors.DictCursor」 一個列表,而不是的數組被返回,所以你可以用他們的鍵名來引用數據,這在你的情況下是姓氏。