简体   繁体   English

Python:从sqlite3中提取文本作为字符串

[英]Python: Extract TEXT from sqlite3 as a string

First week programming in any language and need some help: Im trying to extract a TEXT value as a string from sqlite3 in Python. 使用任何语言进行编程的第一周,都需要一些帮助:我试图从python的sqlite3中提取一个TEXT值作为字符串。 Im getting a value as a list not a str: 我得到一个值作为列表而不是一个str:

system_id = raw_input ("What is your System ID: ")

For example the user enters 'Elmer' 例如,用户输入“ Elmer”

conn = sqlite3.connect("API.db")
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS SYSTEMID (systemid TEXT)''')
conn.commit()
conn.close()

conn = sqlite3.connect("API.db")
c = conn.cursor()
system_id = c.execute('select systemid from SYSTEMID').fetchall()
conn.close()

So how to make the variable system_id as a string? 那么如何使变量system_id作为字符串呢? If I print from this I get something like [(u, Elmer)], I want system_id = Elmer 如果从中打印,我会得到类似[[u,Elmer)]的信息,我希望system_id = Elmer

As pointed out by Ev. 正如Ev所指出的 Kounis , fetchall() by default will return a list of tuple s with length equal to the variables specified. 默认情况下, Kounisfetchall()将返回一个tuple list ,其长度等于指定的变量。

In your case you are getting a tuple of length 1, because you asked for a single variable. 在您的情况下,您将得到长度为1的元组,因为您需要一个变量。

The u in front of the string 'Elmer' is also returned by default when getting strings (this just means it is a Unicode String). 获取字符串时,默认情况下还会返回字符串'Elmer'前面的u (这仅表示它是Unicode字符串)。

There are two things you should do: 您应该做两件事:

  1. Get rid of u by changing text_factor of the connection to str like this: 通过将连接的text_factor更改为str来摆脱u ,如下所示:

     con.text_factory = str 
  2. Accessing first element of the tuple to only get the string 'Elmer' : 访问元组的第一个元素只能得到字符串'Elmer'

    fetch = c.execute('select systemid from SYSTEMID').fetchall()
    system_id = fetch[0][0] # First element in first tuple in list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM