python - 将数据输入 SQLite

标签 python mysql database sqlite serial-port

我正在处理一个项目并启动了一个小项目以通过串行获取一些数据。数据来自串行,但没有任何内容添加到数据库中。创建表,但不会推送实际数据。那里出了点问题。

这是我的代码:

#!/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

最佳答案

尝试添加

db_connection.commit()

在您的 INSERT 语句之后。

关于python - 将数据输入 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15381526/

相关文章:

php - 写入 mysql 数据库 PHP。如何更新字段中的值?

sql - 使用 row_number() 的列名无效 OVER(PARTITION BY )

python re.search regex - 如何在字符串的最后 4 位中搜索值

Mysql Server 守护程序打开或访问太多文件是一个问题

python - Pandas 数据框应用具有 iterrows 的函数

php - 字符在 mysql 中显示为乱码(希伯来语)

database - 在数据库列中存储分隔列表真的那么糟糕吗?

database - 甲骨文顶点 : Create a progress bar when waiting result

python - 如何在 Django 和 Wagtail 中翻译 .js 文件

python - 如何有效地操作子数组,例如计算行列式、逆矩阵、