python - 有谁知道如何将 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
现在我想从我的存储中取回数据。有谁知道如何将一列取回数组。
解决方案
我不知道您使用的是 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')
希望这可以帮助!
推荐阅读
- c++ - 实现相同接口的对象/类之间的 C++ 数据共享
- amazon-web-services - aws 私有子网连接
- prolog - 如何从序言中的跟踪中读取绘制搜索树?
- javascript - 仅在 chrome-dev-tool 中单击“检查”后渲染 vue-carousel-3d
- java - 即使我在依赖项中添加了编译方法也无法解析 FileUtils
- php - 自定义 Wordpress 循环中的日期不正确
- jquery - 在 select2 上搜索时调用 ajax
- maven - Maven 多模块项目
- delphi - 将新文件添加到项目时如何自动保存 DPR 文件
- sql - 使用 Postgres 进行“多个”搜索