用于从关系数据库检索数据的Python SQL查询

时间:2015-10-05 09:56:20

标签: python mysql relational-database mariadb

我有以下数据库表:

SENSORS: sensor_id, type_id, location_id, pin_id
SENSOR_TYPES:type_id, type_name, parameter
LOCATIONS: location_id, room
PI_PINS: pin_id, broadcom, wiring_pi, description

通过x_id字段在SENSORS和其他三个表之间建立了关系。

如何构造python代码来运行将返回包含{sensor_id:type_name}的dict的SQL查询?我认为以下查询应该可以工作,但我不知道如何在python中包装它以返回一个字典。

SELECT sensors.sensor_id, sensor_types.type_name
FROM sensors
INNER JOIN sensor_types
ON sensors.type_id=sensor_types.type_id

1 个答案:

答案 0 :(得分:0)

好的,原来这里有一个dict游标。对于后代,这是我的工作代码:

#!/usr/bin/env python

import MySQLdb

# Open databse connection
db = MySQLdb.connect(host="****",user="****",passwd="****",db="****")

#Prepare a cursor object using cursor() method
cur = db.cursor(MySQLdb.cursors.DictCursor)

#Execute SQL query using execute() method
cur.execute("SELECT sensor_id, sensor_types.type_name FROM sensors INNER JOIN sensor_types ON sensors.type_id=sensor_types.type_id")

#Fetch the results
data = cur.fetchall()

#Print out results
for row in data:
    print row["sensor_id"],row["type_name"]

#Disconnect from server
db.close()