Chủ Nhật, 23 tháng 4, 2017

Python post json to InfluxDB, import export Oracle

1. Update pip, install influxdb:
#python3.5
#pip install --upgrade pip
#pip install influxdb
#python3.5 -m pip install cx_Oracle --pre


Content of file:
#!/usr/bin/env python
# -*- coding: utf-8 -*-


from influxdb import InfluxDBClient

json_body = [
    {
        "measurement": "cpu_load_short",
        "tags": {
            "host": "server01",
            "region": "us-west"
        },
        "time": "2009-11-10T23:00:00Z",
        "fields": {
            "value": 0.64
        }
    }
]

client = InfluxDBClient('localhost', 8086, 'admin', '123456', 'example')

client.create_database('example')

client.write_points(json_body)

result = client.query('select value from cpu_load_short;')

print("Result: {0}".format(result))



2. Collect data Oracle by Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cx_Oracle
import os


ORACLE_CONNECT=('operator11/operator123111@172.11.2.10:1521/lstaaa')
orcl = cx_Oracle.connect(ORACLE_CONNECT)
print("Connected to Oracle: " + orcl.version)

sql = "  select * from example"
curs = orcl.cursor()
curs.execute(sql)

for row in curs:
    print(row)


* Một cách kết nối khác nếu đã khai báo oracle:
from libraries.oracledb import OracleLIB

ORACLE_CONNECT = OracleLIB().connect()
sql = "select * from VH_CRONTAB_MANAGER"
curs.execute(sql)

for row in curs:
    print(row)

Có thể hiểu đơn giản như sau:
   1. khai báo sẵn thư viện kết nối oracle: from libraries.oracledb import OracleLIB
   2. Khai báo kết nối = thư viện.connect: ORACLE_CONNECT = OracleLIB().connect()
   3. Đặt Current = kết nối.contrỏ():   curs = ORACLE_CONNECT.cursor()



3. Python insert Database:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cx_Oracle
import os
import csv

#dsn_tns = cx_Oracle.makedsn('ltest-scan.mservice.com.vn/ltest.mservice.com.vn', 1521, 'ltest.mservice.com.vn')   => with SID
#dbCon = cx_Oracle.connect('operator', 'operator123', dsn_tns)

ORACLE_CONNECT=('operator/operator123@ltest-scan.mservice.com.vn:1521/ltest.mservice.com.vn')     => with Service name
dbCon = cx_Oracle.connect(ORACLE_CONNECT)

cursor = dbCon.cursor()

list = []
f = open('/vanhanh/tools/example.csv','r')

# srid must be a valid code in sde.st_spatial_references
cursor.prepare("""INSERT INTO VH_NAPAS (TID,CREDITOR,TIDNAPAS,CREATED,MSRESULT,PARTNERRESULT) VALUES (:1,:2,:3,:4,:5,:6)""")
for line in f:
    pair = line.split(';')
    list.append((pair[0],pair[1],pair[2],pair[3],pair[4],pair[5]))

#print cursor.bindnames()
cursor.executemany(None, list)
dbCon.commit()
f.close()
cursor.close()
dbCon.close()

Không có nhận xét nào:

Đăng nhận xét