首页 > 解决方案 > 有谁知道如何将 sqllite 中数据库上的列提取到数组中?

问题描述

我在python中有数组,例如:

Temperature = ([34, 23.4, 25.5, 16.7])
Humidity = ([89, 93, 78, 59, 61)]

我已将它们作为 .db 文件存储在 SQLlite 中

Temperature  Humidity
34            89
23.4          93
25.5          78
25.5          59
16.7          61

现在我想从我的存储中取回数据。有谁知道如何将一列取回数组。

数据库.db

标签: pythonsqlite

解决方案


我不知道您使用的是 SQLite 还是 MySQL,但是方法将是相同的,即使不是非常相似。

您需要做的第一件事是在 python 中与您的数据库建立连接。如果您使用的是 mySQL,则需要导入一个库。建立连接后,您将需要设置一个游标,使您能够使用数据库功能。

#This is for a mySQL database
import mysql.connector

conn = mysql.connector.connect(host='#Your hose name goes here',
                               user='#your user name goes here',
                               password='#your password goes here',
                               db='#name of your db goes here')

#This cursor enables database functions
cur = conn.cursor()

cur.execute('USE #enter database name here;')
cur.execute('SELECT Temperature FROM #insert name of database here;')

#To access the column we will store the data from the Temperature column into the  
#temperature var

temperature=cur.fetchall()

#Create an empty array 
temp_data=[]

#The for loop will be used to iterate through the data in the Temperature column
#and store it in the array
for data in temperature:
    temp_data.append(data)

如果您使用 SQLite,您将需要一个不同的库来连接到您的数据库。您只需像这样连接到您的数据库:

import sqlite3
conn= sqlite3.connect('#name of your file.db')

希望这可以帮助!


推荐阅读