Advertisement
CptAwe

query sender

Mar 28th, 2019
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. import psycopg2
  2. import pandas as pd
  3. import numpy as np
  4.  
  5. def send_query(settings, query):
  6.     '''
  7.     \r[GeoPap]
  8.     \rIt sends the query to the database
  9.     '''
  10.  
  11.     if settings==None: raise ValueError("No settings provided")
  12.     if query==None: raise ValueError("No query provided")
  13.  
  14.     # Delete invalid characters
  15.     invalid_char="\n\t"
  16.     for char in invalid_char:
  17.         query=query.replace(char," ")
  18.  
  19.     # Repace 2 or more consecutive spaces with only one space
  20.     query=" ".join(query.split())
  21.  
  22.  
  23.     print("[send_query][MSG] Sending query:\n\t%s"%(query))
  24.  
  25.    
  26.    
  27.     with psycopg2.connect(**settings) as conn:
  28.         with conn.cursor() as cur:
  29.             try:
  30.                 cur.execute(query)
  31.                 data=cur.fetchall()
  32.                 answer=pd.DataFrame(data)
  33.                 print("[send_query][MSG] Got an answer!")
  34.             except Exception as error:
  35.                 print("[send_query][ERR] %s"%(error))
  36.                 answer=""
  37.  
  38.     return answer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement