Amazon Ads

2015年6月9日 星期二

【筆記】在Ubuntu 14.04中,用python來連線並查詢MySQL中的資料

先到這裡下載mysql-connector-python_2.0.4-1debian7.6_all.deb
wget http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python_2.0.4-1debian7.6_all.deb
並將其安裝:
sudo dpkg -i mysql-connector-python_2.0.4-1debian7.6_all.deb
安裝完成後,就開始來寫程式吧!這裡將程式存成mysql_query.py
#!/usr/bin/python
import mysql.connector
cnx = mysql.connector.connect(user='cbuser', password='cbpass',
                              host='127.0.0.1',
                              database='cookbook')

cursor = cnx.cursor();
query = "select a, b from test"
cursor.execute(query)

for(a, b) in cursor:
        print("column a is {}, column b is {}".
                format(a, b))

cursor.close()
cnx.close()
test這個資料表中的資料如下:
+---+------+
| a | b    |
+---+------+
| 1 | abc  |
| 2 | xyz  |
+---+------+
最後執行程式:
python mysql_query.py 
執行結果為:
column a is 1, column b is abc
column a is 2, column b is xyz

沒有留言: