如果您想有計畫地處理大量資料,我想您需要一個資料庫軟體來處理這件事情,而 MySQL 就是最佳的選擇之一。
目前 MySQL 為 3.23 版,支援 Python 2.4~2.7 版,未來才會支援 Python 3.x 版。
下載
切換到下載頁 http://sourceforge.net/projects/mysql-python/?source=dlp,點擊綠色的 Download 按鈕。
安裝
雙擊 MySQL-python-1.2.4b4.win32-py2.7.exe,然後依照視窗內的指示進行安裝。
首先用 MySQL 建立一個含有溫濕度數據的氣象資料表,如下:
create table weatherData (
weatherDataID int(11) AUTO_INCREMENT NOT NULL,
humidity decimal(4,2) NOT NULL,
tempC decimal(4,2) NOT NULL,
constraint weatherData_PK primary key (weatherDataID)
);
Python Code
#!/usr/bin/python
import serial
import MySQLdb
#establish connection to MySQL. You'll have to change this for your database.
dbConn = MySQLdb.connect("localhost","database_username","password","database_name") or die ("could not connect to database")
#open a cursor to the database
cursor = dbConn.cursor()
device = 'COM5' #this will have to be changed to the serial port you are using
try:
print "Trying...",device
arduino = serial.Serial(device, 9600)
except:
print "Failed to connect on",device
try:
data = arduino.readline() #read the data from the arduino
pieces = data.split("\t") #split the data by the tab
#Here we are going to insert the data into the Database
try:
cursor.execute("INSERT INTO weatherData (humidity,tempC) VALUES (%s,%s)", (pieces[0],pieces[1]))
dbConn.commit() #commit the insert
cursor.close() #close the cursor
except MySQLdb.IntegrityError:
print "failed to insert data"
finally:
cursor.close() #close just incase it failed
except:
print "Failed to get data from Arduino!"
沒有留言:
張貼留言