一般来说各个数据库的sql都是一样的语法,但还是说明一下这里的是postgres数据库。
下列示例中,
param_maintain是table,
type, param, param_value, unit, start_use_time, maintain_time是列名。
示例代码
def get_conn_pg():
f = open(r'./config.yaml', encoding='utf-8')
config_param = yaml.load(f.read(), Loader=yaml.FullLoader).get('postpsql')
conn = psycopg2.connect(host=config_param.get('host'),
port=config_param.get('port'),
user=config_param.get('user'),
password=config_param.get('password'),
database=config_param.get('database'))
cur = conn.cursor()
return conn, cur
def close_conn_pg(cur, conn):
cur.close()
conn.close()
conn, cur = get_conn_pg()
table = 'param_maintain'
sql_select = f""" select * from "{table}" where type = '04' """
cur.execute(sql_select)
# conn.commit()
data_list = cur.fetchall()
fields = [desc[0] for desc in cur.description]
close_conn_pg(cur, conn)
df_db_params = pd.DataFrame(data_list)
df_db_params.columns = fields
tips:
查询不需要commit。增删改需要commit,提交事务,操作真正会影响到数据库中,否则数据库数据不变。