python获取数据库列名_python sqlite3 查询操作及获取对应查询结果的列名
記錄查詢操作及獲取查詢結(jié)果列字段的方法
1.sqlite3 中獲取所有表名及各表字段名的操作方法
SQLite 數(shù)據(jù)庫中有一個特殊的表叫 sqlite_master,sqlite_master 的結(jié)構(gòu)如下:
CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);
可以通過查詢這個表來獲取數(shù)據(jù)庫中所有表的信息
SELECT * FROM sqlite_master WHERE type='table';
查詢某張表的所有字段
PRAGMA table_info(表名);
示例:
PRAGMA table_info(sqlite_sequence);
2. python 操作sqlite3,獲取sql 查詢結(jié)果及對應(yīng)查詢結(jié)果的列名的方法
class DBOperate(object):
"""
數(shù)據(jù)庫操作類
"""
def __init__(self, db_file_path):
# 連接 sqlite db
# 關(guān)于commit(),如果isolation_level隔離級別默認(rèn),那么每次對數(shù)據(jù)庫的操作,都需要使用該命令,
# 設(shè)置 isolation_level=None,變?yōu)樽詣犹峤荒J?/p>
self._db_file_path = db_file_path
self.conn = sqlite3.connect(self._db_file_path, check_same_thread=False, isolation_level=None, timeout=1000)
# 創(chuàng)建游標(biāo)
self.cur = self.conn.cursor()
def queryall(self, sql):
"""
查詢所有的數(shù)據(jù)及對應(yīng)的列名
:param sql:
:return:
"""
self.cur.execute(sql)
# TODO 獲取查詢結(jié)果的列名
columns_tuple = self.cur.description
# columns_tuple示例: (('TACHE_NAME', None, None, None, None, None, None), ('avgtime', None, None, None, None, None, None), ('DATE', None, None, None, None, None, None), ('ANALYSIS_TIME', None, None, None, None, None, None))
columns_list = [field_tuple[0] for field_tuple in columns_tuple]
# TODO 獲取查詢結(jié)果
query_result = self.cur.fetchall()
return query_result, columns_list
def close(self):
"""
關(guān)閉數(shù)據(jù)庫連接
:return:
"""
if self.cur is not None:
self.cur.close()
if self.conn is not None:
self.conn.close()
總結(jié)
以上是生活随笔為你收集整理的python获取数据库列名_python sqlite3 查询操作及获取对应查询结果的列名的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css不换行属性_那些不常见,但却非常实
- 下一篇: 好的u盘连接电脑没反应怎么回事 U盘与电