隨筆記:Python於Windows下初實踐,及使用Connector/Python連接MySQL


有一同事要離職了,我負責交接一個用Python同步數據的項目。

之前木有做過Python,周休,做個簡單的查詢數據庫,小練一下手。

包含:

  1. 安裝
  2. 連接、查詢MySQL
  3. 列表
  4. 元組
  5. for循環
  6. while循環

 

下載

上Python官方網站,下載Python安裝包,目前流行的版本為2.7和3.x版本,這兩個大版本之間語法有些差異,並不兼容。

這次項目用到的是2.7版本,所以,先學習此。

目前,下載頁面為:https://www.python.org/downloads/release/python-279/

 

安裝

windows的安裝步驟與普通軟件一致,安裝完成后,需將python目錄設置(用“追加”來形容可能更合適)到PATH中。

再用命令查看其版本,以確認是否成功安裝

python -v
View Code

 

hello world,少不了的hello world

#!/usr/bin/python

# output HELLO WORLD
print 'HELLO WORLD.';
View Code

 

這次的需求是連接Mysql。

首先,下載並安裝MySQL的Connector/Python

目前,可從此頁面下載:http://dev.mysql.com/downloads/connector/python/1.0.html

與普通軟件安裝無異。

 

編寫腳本

連接數據庫,並查詢數據

#coding=utf-8
#!/usr/bin/python
import mysql.connector;

try:
    conn = mysql.connector.connect(host='172.0.0.1', port='3306', user='username', password="123456", database="testdev", use_unicode=True);
    cursor = conn.cursor();
    cursor.execute('select * from t_user t where t.id = %s', '1');
    # 取回的是列表,列表中包含元組
    list = cursor.fetchall();
    print list;

    for record in list:
        print "Record %d is %s!" % (record[0], record[1]);

except mysql.connector.Error as e:
    print ('Error : {}'.format(e));
finally:
    cursor.close;
    conn.close;
    print 'Connection closed in finally';
View Code

 

運行腳本

直接運行此py腳本就可以了

018.連接MYSQL.py
View Code

 

fetchall函數返回的是[(xxx, xxx)]的記錄,數據結構為“列表(中括號[])包含元組(小括號())”。此二屬於常用的集合。

列表

就像JAVA的List,即,有序的;可包含不同類型元素的

#coding=utf-8
#!/usr/bin/python

list = ['today', 'is', 'sunday'];
index = 0;
for record in list:
    print str(index) + " : " + record;
    index = index + 1;
View Code

 

結果:

d:\python27_workspace>"04.list type.py"
0 : today
1 : is
2 : sunday
View Code

 

元組

與列表類型,只是元組的元素不能修改

#coding=utf-8
#!/usr/bin/python

tuple = ('today', 'is', 'sunday');

# TypeError: 'tuple' object does not support item assignment
# tuple[1] = 'are';

index = 0;
while (index < len(tuple)):
    print str(index) + " : " + tuple[index];
    index = index + 1;
View Code

 

圍繞着連接、查詢MySQL這個需求,算是對Python作了一個初步的認識與實踐。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM