[英]Writing column names to file
I have an SQLite DB file and I am parsing the data from each column in a table of the db to a .txt file. 我有一个SQLite DB文件,我正在将数据库表中每一列的数据解析为.txt文件。 At the moment it is writing the column contents to the file but it won't pull the column names and write those. 目前,它正在将列内容写入文件,但不会拉出列名称并写入它们。 How can I go about it as I have tried to use this guide Is there a way to get a list of column names in sqlite? 当我尝试使用本指南时,该如何处理?是否有办法获取sqlite中的列名列表? but i cannot seem to get it to work. 但我似乎无法使其正常工作。 Here is my code with an attempt at pulling the column names from the table. 这是我的代码,试图从表中提取列名。
import sqlite3
from sqlite3 import Error
# create a database connection to the SQLite database specified by the db_file
def create_connection(db_file,detect_types=sqlite3.PARSE_DECLTYPES):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
# Query specific rows in the sms table
def select_data(conn):
cur = conn.cursor()
cur.execute("SELECT _id, address, strftime('%d-%m-%Y', date / 1000, 'unixepoch'),read, type, body, seen FROM sms")
print("Writing the contents of the sms table to an evidence file")
print("\t")
# Trying to pull out column names from db table
def get_col_names():
conn = sqlite3.connect("mmssms.db")
c = conn.cursor()
c.execute("SELECT _id, address, strftime('%d-%m-%Y', date / 1000, 'unixepoch'),read, type, body, seen FROM sms")
return [member[0] for member in c.description]
# Write the data to a smsEvidence.txt file
with open('EvidenceExtractionFiles/smsInfo.txt', 'a+') as f:
rows = cur.fetchall()
for row in rows:
#print(row)
f.write("%s\n" % str(row))
print("SMS Data is written to the evidence File")
# path to where the db files are stored
def main():
database = "H:\College Fourth Year\Development Project\Final Year Project 2018\mmssms.db"
# create a database connection
conn = create_connection(database)
with conn:
# print("Query specific columns")
select_data(conn)
# close db connection
if(conn):
conn.close()
print("Database closed")
if __name__ == '__main__':
main()
You may use cursor.description
which holds info about the column names: 您可以使用cursor.description
,其中包含有关列名的信息:
[ ... ] [...]
cur = cursor.execute('SELECT * FROM test_table LIMIT 100')
col_names = [ name[0] for name in cur.description ]
print (col_names)
[ ... ] [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.