您现在的位置是:网站首页> 编程资料编程资料

python将Dataframe格式的数据写入opengauss数据库并查询_python_

2023-05-26 288人已围观

简介 python将Dataframe格式的数据写入opengauss数据库并查询_python_

一、将数据写入opengauss

前提准备:

成功opengauss数据库,并创建用户jack,创建数据库datasets。

数据准备:

所用数据以csv格式存在本地,编码格式为GB2312。

数据存入:

开始hello表未存在,那么执行程序后,系统会自动创建一个hello表(这里指定了名字为hello);

若hello表已经存在,那么会增加数据到hello表。列名需要与hello表一一对应。

# 加载必要的python库 from sqlalchemy import create_engine import pandas as pd   # 从本地读入数据 df = pd.read_csv("E:/jiema.csv",low_memory=False,encoding='gb2312')   #创建数据库引擎 #create_engine说明:driver://user:password@host:port/dbname engine = create_engine('postgresql://jack:gauss@111@192.168.80.130:26000/datasets')   #写入数据 try:     df.to_sql('hello',engine,index=False,if_exists='append')  #hello为创建的数据库表名字 except Exception as e:     print(e)

使用navicat查看效果:

二、python条件查询opengauss数据库中文列名的数据

问题:

由于项目要求,数据库中的列名都是以中文命名的,导致在后期查询的时候出现了很多问题。

解决方法:

 整条SQL语句需要用单引号包裹,中文列名需要用双引号包裹起来。

import psycopg2   def dataFromDB(sql):     # 连接数据库     conn = psycopg2.connect(database='datasets', user='jack', password='gauss@111', host='192.168.80.130', port='26000')     curs = conn.cursor()       # 编写Sql,只取前两行数据     # sql = 'select * from table_name limit 2'       # 数据库中执行sql命令     curs.execute(sql)     # 获得数据     data = curs.fetchall()     print(data)       # 关闭指针和数据库     curs.close()     conn.close()   sql ='SELECT "遥测参数2", "遥测参数2路温度" from source2decode where "工程参数.源地址" =26 '   dataFromDB(sql)

到此这篇关于python将Dataframe格式的数据写入opengauss数据库并查询的文章就介绍到这了,更多相关python将数据写入opengauss内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网