欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python將Dataframe格式的數(shù)據(jù)寫入opengauss數(shù)據(jù)庫并查詢

 更新時間:2022年04月12日 18:28:36   作者:摸魚的胖七七  
這篇文章主要介紹了python將Dataframe格式的數(shù)據(jù)寫入opengauss數(shù)據(jù)庫并查詢,文章介紹詳細具有一定的參考價值,希望對你的學習有所幫助

一、將數(shù)據(jù)寫入opengauss

前提準備:

成功opengauss數(shù)據(jù)庫,并創(chuàng)建用戶jack,創(chuàng)建數(shù)據(jù)庫datasets。

數(shù)據(jù)準備:

所用數(shù)據(jù)以csv格式存在本地,編碼格式為GB2312。

數(shù)據(jù)存入:

開始hello表未存在,那么執(zhí)行程序后,系統(tǒng)會自動創(chuàng)建一個hello表(這里指定了名字為hello);

若hello表已經(jīng)存在,那么會增加數(shù)據(jù)到hello表。列名需要與hello表一一對應(yīng)。

# 加載必要的python庫
from sqlalchemy import create_engine
import pandas as pd
?
# 從本地讀入數(shù)據(jù)
df = pd.read_csv("E:/jiema.csv",low_memory=False,encoding='gb2312')
?
#創(chuàng)建數(shù)據(jù)庫引擎
#create_engine說明:driver://user:password@host:port/dbname
engine = create_engine('postgresql://jack:gauss@111@192.168.80.130:26000/datasets')
?
#寫入數(shù)據(jù)
try:
? ? df.to_sql('hello',engine,index=False,if_exists='append') ?#hello為創(chuàng)建的數(shù)據(jù)庫表名字
except Exception as e:
? ? print(e)

使用navicat查看效果:

二、python條件查詢opengauss數(shù)據(jù)庫中文列名的數(shù)據(jù)

問題:

由于項目要求,數(shù)據(jù)庫中的列名都是以中文命名的,導致在后期查詢的時候出現(xiàn)了很多問題。

解決方法:

 整條SQL語句需要用單引號包裹,中文列名需要用雙引號包裹起來。

import psycopg2
?
def dataFromDB(sql):
? ? # 連接數(shù)據(jù)庫
? ? conn = psycopg2.connect(database='datasets', user='jack', password='gauss@111', host='192.168.80.130', port='26000')
? ? curs = conn.cursor()
?
? ? # 編寫Sql,只取前兩行數(shù)據(jù)
? ? # sql = 'select * from table_name limit 2'
?
? ? # 數(shù)據(jù)庫中執(zhí)行sql命令
? ? curs.execute(sql)
? ? # 獲得數(shù)據(jù)
? ? data = curs.fetchall()
? ? print(data)
?
? ? # 關(guān)閉指針和數(shù)據(jù)庫
? ? curs.close()
? ? conn.close()
?
sql ='SELECT "遙測參數(shù)2", "遙測參數(shù)2路溫度" from source2decode where "工程參數(shù).源地址" =26 '
?
dataFromDB(sql)

到此這篇關(guān)于python將Dataframe格式的數(shù)據(jù)寫入opengauss數(shù)據(jù)庫并查詢的文章就介紹到這了,更多相關(guān)python將數(shù)據(jù)寫入opengauss內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論