0
我正在使用一個項目,並啓動了一個小型項目以通過串行獲取一些數據。數據通過串行傳輸,但沒有任何內容被添加到數據庫中。表格被創建,但不是實際的數據被推送。那裏出了點問題。在SQLite中輸入數據
這裏是我的代碼:
#!/usr/bin/env python
import serial
import time
import sqlite3
import os
from datetime import datetime
conn = sqlite3.connect("elements78.db") # or use :memory: to put it in RAM
cursor = conn.cursor()
sql_file = os.path.join(os.path.dirname(__file__), 'elements78.db')
needs_creation = not os.path.exists(sql_file)
db_connection = sqlite3.connect(sql_file)
db_connection.row_factory = sqlite3.Row
# create a table
if needs_creation:
print 'Creating initial database...'
cursor = db_connection.cursor()
db_connection.commit()
print 'Database created.'
cursor.executescript("""
DROP TABLE IF EXISTS elements;
CREATE TABLE elements (id INTEGER PRIMARY KEY AUTOINCREMENT, Name, date CURDATE)
""")
#enter your device file
arddev = '/dev/tty.usbmodem621'
baud = 9600
#setup - if a Serial object can't be created, a SerialException will be raised.
while True:
try:
ser = serial.Serial(arddev, baud)
#break out of while loop when connection is made
break
except serial.SerialException:
print 'waiting for device ' + arddev + ' to be available'
time.sleep(3)
#read lines from serial device
count = 0
while count < 5:
element = ser.readline().strip('\n')
count = count + 1
datestamp = datetime.now()
print 'received the element: ' + element
print datestamp
cursor.execute('insert into elements(Name) values("%s")'%(element))
allentries = []
cursor.execute('SELECT * FROM elements')
allentries=cursor.fetchall()
print allentries
也許這可能會給你一些建議http://zetcode.com/db/sqlitepythontutorial/ – Mingebag 2013-03-13 09:39:50
我*真的很真*建議你使用'sqlalchemy'包 – 2013-03-13 09:42:55
Jakub M的好建議,sqlalchemy會讓你的生活變得更加美好在這種情況下更容易,它也是一個ORM! – theBigChalk 2013-03-13 22:39:30