3

SQLite query through Python returns strange variable name

I'm using the following Python code to query a SQLite output file produced by EnergyPlus:

import sqlite3
import os

sqlite_file = './test_sql_h.sql'

table_name = 'ReportDataDictionary'
id_column = 'ReportDataDictionaryIndex'
column_a = 'Name'
column_b = 'KeyValue'

# connect to the database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()

# identify all unique variable names
c.execute(
        ' SELECT DISTINCT ({col}) FROM {tn} '.\
        format(tn=table_name, col=column_a)
        )
all_names_unique = c.fetchall()
for i in range(0, len(all_names_unique)):
    print(all_names_unique[i])

# commit changes and queries, and close the connection
conn.commit()
conn.close()

However, each variable name is enclosed in a pair of single quotation marks proceeded by the letter "u" as shown below.

(u'Zone Lights Electric Energy',)
(u'Zone Electric Equipment Electric Energy',)
(u'Zone Ideal Loads Supply Air Total Heating Energy',)
(u'Zone Ideal Loads Supply Air Total Cooling Energy',)

May I ask why the output is not the pure name of the variable?

Thanks.

oat's avatar
835
oat
asked 2017-10-29 01:07:01 -0500
__AmirRoth__'s avatar
4.4k
__AmirRoth__
updated 2017-11-10 08:10:39 -0500
edit flag offensive 0 remove flag close merge delete

Comments

add a comment see more comments

1 Answer

3

This is because strings retrieved from sqlite database are Unicode instead of UTF-8. Following changes should get rid of prefix u.

conn = sqlite3.connect(sqlite_file)
conn.text_factory = str
c = conn.cursor()

Suggested readings: 1, 2, 3, 4

Chandan Sharma's avatar
2.4k
Chandan Sharma
answered 2017-10-29 05:00:55 -0500
edit flag offensive 0 remove flag delete link

Comments

Thank you very much, Chandan, for your detailed advice. Will learn from the sources your suggested.

oat's avatar oat (2017-10-29 06:49:53 -0500) edit
add a comment see more comments