【问题标题】:How to make fetch methods return int values for INTEGER columns instead of strings Python sqlite?如何使 fetch 方法返回 INTEGER 列的 int 值而不是字符串 Python sqlite?
【发布时间】:2023-04-04 11:44:01
【问题描述】:

我正在尝试使用此代码从 sqlite 数据库列中读取所有温度值,但输出显示 [(u'29',), (u'29',), (u'29',)] 并且我仅将数值存储在数据库中。我希望输出为[29, 29, 29]

import sqlite3

conn = sqlite3.connect("growll.db")
cursor = conn.cursor()

print "\nHere's a listing of all the records in the table:\n"
cursor.execute("select lchar from GrowLLDados")

print cursor.fetchall() 

【问题讨论】:

  • 如果这是输出,那么 - 确定 只存储数字? (与数字字符串相反。)SQLite 将根据列类型进行一些基本的类型关联转换,但除此之外,您得到的是数据库中的内容。

标签: python sqlite


【解决方案1】:

试试这个:

import sqlite3

conn = sqlite3.connect("growll.db")
cursor = conn.cursor()

print "\nHere's a listing of all the records in the table:\n"
cursor.execute("select lchar from GrowLLDados")    

print [int(record[0]) for record in cursor.fetchall()]

【讨论】:

  • 完美运行!谢谢,因为我正在学习 python,如果我的数据是像 L 这样的字符而不是 29,你知道我会怎么做吗?
  • 当然:例如,如果 fetchall() 返回 [(u'L',), (u'L',), (u'L',)]print [record[0] for record in cursor.fetchall()] 应该可以工作。顺便说一句,字符串前面的u 只是表示它们是unicode 字符串。
  • 要使用此数据,我如何将其存储在新变量中,因为如果我尝试读取记录变量,则只有最后读取的变量而不是列表。谢谢
  • 要将[29, 29, 29] 放入变量中,请将其分配给一个变量而不是打印它,即records = [int(record[0]) for record in cursor.fetchall()]。是这个意思吗?
  • 是的,我将使用 matplot 处理这些数据。
【解决方案2】:

print [int(i[0]) for i in cursor.fetchall()]

让我知道你过得怎么样。

【讨论】:

  • 这不会抛出 TypeError 吗? int() 需要一个字符串,而不是一个元组
  • 是的,我有:TypeError: int() argument must be a string or a number, not 'tuple'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 2019-09-15
  • 2012-04-30
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2019-08-08
相关资源
最近更新 更多