将数据导入数据库并检索

时间:2016-02-09 08:23:59

标签: python database

我有一个raspberrypi,每隔5分钟就会在python中运行数据。我需要使用wamp服务器将数据存储到数据库,并将其绘制在图表中(时间与数据)。我不知道如何连接到wamp服务器来存储和检索数据。

1 个答案:

答案 0 :(得分:0)

取自https://github.com/PyMySQL/PyMySQL

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
        connection.close()