def run_test_116(self):
        conn = None
        is_alive = ibm_db.active(conn)
        if is_alive:
            print("Is active")
        else:
            print("Is not active")

        conn = ibm_db.connect(config.database, config.user, config.password)
        is_alive = ibm_db.active(conn)
        if is_alive:
            print("Is active")
        else:
            print("Is not active")

        ibm_db.close(conn)
        is_alive = ibm_db.active(conn)
        if is_alive:
            print("Is active")
        else:
            print("Is not active")

        # Executing active method multiple times to reproduce a customer reported defect
        print(ibm_db.active(conn))
        print(ibm_db.active(conn))
        print(ibm_db.active(conn))
        conn = ibm_db.connect(config.database, config.user, config.password)
        print(ibm_db.active(conn))
        print(ibm_db.active(conn))
        print(ibm_db.active(conn))
  def run_test_116(self):
    conn = None
    is_alive = ibm_db.active(conn)
    if is_alive:
      print("Is active")
    else:
      print("Is not active")

    conn = ibm_db.connect(config.database, config.user, config.password)
    is_alive = ibm_db.active(conn)
    if is_alive:
      print("Is active")
    else:
      print("Is not active")

    ibm_db.close(conn)
    is_alive = ibm_db.active(conn)
    if is_alive:
      print("Is active")
    else:
      print("Is not active")

    # Executing active method multiple times to reproduce a customer reported defect
    print(ibm_db.active(conn))
    print(ibm_db.active(conn))
    print(ibm_db.active(conn))
    conn = ibm_db.connect(config.database, config.user, config.password)
    print(ibm_db.active(conn))
    print(ibm_db.active(conn))
    print(ibm_db.active(conn))
def dashdB_Init():
	global connection,url
	dbtry = 0
	while(dbtry <3):
		try:
			if 'VCAP_SERVICES' in os.environ:
			    hasVcap = True
			    import json
			    vcap_services = json.loads(os.environ['VCAP_SERVICES'])
			    if 'dashDB' in vcap_services:
			        hasdashDB = True
			        service = vcap_services['dashDB'][0]
			        credentials = service["credentials"]
			        url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % ( credentials["db"],credentials["username"],credentials["password"],credentials["host"],credentials["port"])
			    else:
			        hasdashDB = False
			  
			else:
			    hasVcap = False
			    url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % (DB_NAME,DB_USER_NAME,DB_PASSWORD,DB_HOST,DB_PORT)
   
			connection = ibm_db.connect(url, '', '')
			if (active(connection)):
				return connection
		except Exception as dberror:
			logging.error("dberror Exception %s"%dberror)
			dbtry+=1
	return False
def dB_init():
	dbtry = 0
	while (dbtry < 3):
		try:
			if 'VCAP_SERVICES' in os.environ:
			    hasVcap = True
			    import json
			    vcap_services = json.loads(os.environ['VCAP_SERVICES'])
			    if 'dashDB' in vcap_services:
			        hasdashDB = True
			        service = vcap_services['dashDB'][0]
			        credentials = service["credentials"]
			        url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % ( credentials["db"],credentials["username"],credentials["password"],credentials["host"],credentials["port"])
			    	print "VCAP",url    
			    else:
			        hasdashDB = False
			else:
			    hasVcap = False
			    url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % (DB_NAME,DB_USER_NAME,DB_PASSWORD,DB_HOST,DB_PORT)
			connection = ibm_db.connect(url, '', '')
			if (active(connection)):
				return connection
		except Exception as error:
			logging.debug("dataBase connection_ERROR : " + str(error))
			dbtry+=1
	return None	
def dB_init():
    dbtry = 0
    while (dbtry < 3):
        try:
            if 'VCAP_SERVICES' in os.environ:
                hasVcap = True
                import json
                vcap_services = json.loads(os.environ['VCAP_SERVICES'])
                if 'dashDB' in vcap_services:
                    hasdashDB = True
                    service = vcap_services['dashDB'][0]
                    credentials = service["credentials"]
                    url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % (
                        credentials["db"], credentials["username"],
                        credentials["password"], credentials["host"],
                        credentials["port"])
                    print "VCAP", url
                else:
                    hasdashDB = False
            else:
                hasVcap = False
                url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % (
                    DB_NAME, DB_USER_NAME, DB_PASSWORD, DB_HOST, DB_PORT)
            connection = ibm_db.connect(url, '', '')
            if (active(connection)):
                return connection
        except Exception as error:
            logging.debug("dataBase connection_ERROR : " + str(error))
            dbtry += 1
    return None
Exemple #6
0
def dashdB_Init():
	global connection,url
	dbtry = 0
	while(dbtry <3):
		try:
			if 'VCAP_SERVICES' in os.environ:
			    hasVcap = True
			    import json
			    vcap_services = json.loads(os.environ['VCAP_SERVICES'])
			    if 'dashDB' in vcap_services:
			        hasdashDB = True
			        service = vcap_services['dashDB'][0]
			        credentials = service["credentials"]
			        url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % ( credentials["db"],credentials["username"],credentials["password"],credentials["host"],credentials["port"])
			    else:
			        hasdashDB = False
			  
			else:
			    hasVcap = False
			    url = 'DATABASE=%s;uid=%s;pwd=%s;hostname=%s;port=%s;' % (databaseConnectionInfo["Database name"],databaseConnectionInfo["User ID"],databaseConnectionInfo["Password"],databaseConnectionInfo["Host name"],databaseConnectionInfo["Port number"])
			connection = ibm_db.connect(url, '', '')
			if (active(connection)):
				return connection
		except Exception as dberror:
			print "dberror Exception %s"%(dberror)
			dbtry+=1
	return False
Exemple #7
0
 def ExecQuery(self, sql):
     connect = self.GetConnect()
     try:
         stmt = ibm_db.exec_immediate(connect, sql)
         dictionary = ibm_db.fetch_both(stmt)
     except Exception as msg:
         print('stmt Failed', msg)
     finally:
         if ibm_db.active(connect):
             ibm_db.close(connect)
         print("database close success!")
     return dictionary
Exemple #8
0
    def __init__(self, connection, configuration):
        # connection and configuration are passed in the arguments for transmit
        # ex: python main.py transmit db2 '{"host":"localhost", "port":"6603"}' '{"auth": {"mysql_username": "******","mysql_password": "******", "mysql_hostname": "localhost", "mysql_database": "sampledb" } }' pin

        self.auth = configuration.get('auth')
        try:
            self.client = ibm_db.pconnect(
                "DATABASE=" + self.auth.get("mysql_database") + ";HOSTNAME=" +
                connection.get("host", "") + ";PORT=" +
                connection.get("port", "31490") + ";UID=" +
                self.auth.get("mysql_username") + ";PWD=" +
                self.auth.get("mysql_password"), "", "")

            self.state = ibm_db.active(self.client)

        # handle exceptions later TODO
        except Exception as e:
            raise e
Exemple #9
0
def connect_db(dbName):
    if dbName == mrtEnv.IF_DBNM:
        dbUser = mrtEnv.IF_DBUSERNM
        dbPass = mrtEnv.IF_DBPASSWD

    elif dbName == mrtEnv.PLN_DBNM:
        dbUser = mrtEnv.PLN_DBUSERNM
        dbPass = mrtEnv.PLN_DBPASSWD

    try:
        db_conn = ibm_db.connect(dbName, dbUser, dbPass)
        active = ibm_db.active(db_conn)
        print(dbName, u' activation : ', str(active))

        return db_conn
    except:
        print(u'db connect error : ', dbName)
        print(ibm_db.stmt_error())
        print(ibm_db.stmt_errormsg())
        sys.exit()
Exemple #10
0
    def _run(self):
        """
        Run the collector unless it's already running
        """
        if self.collect_running:
            return
        # Log
        self.log.debug("Collecting data from: %s(%s)", self.name, self.__class__.__name__)
        try:
            try:
                start_time = time.time()
                self.collect_running = True

                for db in self.databases:
                    conn = self.connect_db(db)
                    if not conn or not ibm_db.active(conn):
                        break

                    if self.level.upper() == 'INSTANCE':
                        self.collect(conn)
                        break
                    elif self.level.upper() == 'DATABASE':
                        self.collect(conn)

                end_time = time.time()

                if 'measure_collector_time' in self.config:
                    if self.config['measure_collector_time']:
                        metric_name = 'collector_time_ms'
                        metric_value = int((end_time - start_time) * 1000)
                        self.publish(metric_name, metric_value)

            except Exception:
                # Log Error
                self.log.error(traceback.format_exc())
        finally:
            self.collect_running = False
            # After collector run, invoke a flush
            # method on each handler.
            for handler in self.handlers:
                handler._flush()
Exemple #11
0
    def connect_db(self, db, pconnect=True, trytimes=3):
        try:
            if pconnect:
                conn = ibm_db.pconnect(db, "", "")
            else:
                conn = ibm_db.connect(db, "", "")
        except Exception:
            if pconnect:
                self.log.error('Database persistent connect failted('
                    + str(trytimes) + '): ' + traceback.format_exc())
            else:
                self.log.error('Database connect failted('
                    + str(trytimes) + '): ' + traceback.format_exc())

        try:
            if ibm_db.active(conn):
                self.server_info = self.get_server_info(conn)
                return conn
        except Exception:
            pass

        if pconnect:
            self.log.error('Database persistent connect inactive(' + str(trytimes) + ')')
        else:
            self.log.error('Database connect inactive(' + str(trytimes) + ')')

        if trytimes > 0:
            try:
                ibm_db.close(conn)
            except Exception:
                pass
            self.log.info('Database connect try again(' + str(trytimes) + ')')
            trytimes -= 1
            return self.connect_db(db, pconnect=False, trytimes=trytimes)

        return False
Exemple #12
0
def connectionTest():
    connState = ibm_db.active(ibm_db_conn)
    return connState
def connectioncheck_handler():
	global connection,url
	if (active(connection) == False):
		connection = ibm_db.pconnect(url ,'' ,'')
	return None	
Exemple #14
0
passWord = "******"
dbConnection = None
connState = False

# Create An Instance Of The Db2ConnectionMgr Class And Use It To Connect To A Db2 Database
conn = Db2ConnectionMgr('DB', dbName, '', '', userID, passWord)
conn.openConnection()
if conn.returnCode is True:
    dbConnection = conn.connectionID
else:
    conn.closeConnection()
    exit(-1)

# Determine Whether The Current Database Connection Is Active Or Inactive
try:
    connState = ibm_db.active(dbConnection)
except Exception:
    pass

# Display A Status Message That Shows The Current Connection State
print("The connection to the " + dbName + " database is ", end="")
if connState is True:
    print("ACTIVE.\n")
elif connState is False:
    print("NOT ACTIVE.\n")

# Close The Database Connection That Was Opened Earlier
conn.closeConnection()

# Return Control To The Operating System
exit()
Exemple #15
0
def connectioncheck_handler():
	global connection,url
	if (active(connection) == False):
		connection = ibm_db.pconnect(url ,'' ,'')
	return None
Exemple #16
0
 def isAlive(self):
     '''检查是否存活'''
     try:
         return ibm_db.active(self.conn.conn_handler)
     except AttributeError:
         return 0
def AppWeather(event, context):
    try:
        result = False
        request = requests.get(api_str)
        if request.status_code == 200:
            data = request.json()
            # Se extraen los datos necesarios del json
            city_id = data['id']
            city_name = data['name']
            lon = float("{0:.2f}".format(data['coord']['lon']))
            lat = float("{0:.2f}".format(data['coord']['lat']))
            weather = str(data['weather'])
            w = []
            for word in weather.split(","):
                for word1 in word.split(":"):
                    for word2 in word1.split("'"):
                        w.append(word2)
            weather_main = w[8]
            weather_description = w[14]
            # La temperatura está dada en centrigrados, el json lo trae en kelvin por lo cual se transforma
            main_temp = float("{0:.2f}".format(data['main']['temp'] - 273))
            main_temp_min = float("{0:.2f}".format(data['main']['temp_min'] -
                                                   273))
            main_temp_max = float("{0:.2f}".format(data['main']['temp_max'] -
                                                   273))
            # La velocidad del viento está dada en m/s
            wind_speed = float("{0:.2f}".format(data['wind']['speed']))
            wind_deg = float("{0:.2f}".format(data['wind']['deg']))
            wind_direction = "ND"
            # dt es la hora en UTC universal
            dt_unix = data['dt']
            # timezone da el delay con respecto al utc.
            timezone = ((data['timezone']) / 60) / 60
            # preparativos para la hora y la fecha
            date_utc = datetime.datetime.now(datetime.timezone.utc)
            date_wlg = date_utc + timedelta(
                seconds=0, minutes=0, hours=timezone, days=0)
            date_mid = date_utc - timedelta(
                seconds=0, minutes=0, hours=5, days=0)
            # variables con los valores correctos
            current_date_wlg = str(date_wlg.date())
            current_time_wlg = str(date_wlg.time().strftime("%H:%M:%S"))
            current_date_mid = str(date_mid.date())
            current_time_mid = str(date_mid.time().strftime("%H:%M:%S"))
            user_id = getpass.getuser()
            print('Los datos fueron leidos de manera correcta.')
            print("{}".format(user_id))
            # conexion con la db2
            conn = ibm_db.connect(conn_str, '', '')
            if ibm_db.active(conn):
                print('Se establece la conexion con la DB.')
                stmt = ibm_db.prepare(conn, sql_insert)
                ibm_db.bind_param(stmt, 1, city_id)
                ibm_db.bind_param(stmt, 2, city_name)
                ibm_db.bind_param(stmt, 3, lon)
                ibm_db.bind_param(stmt, 4, lat)
                ibm_db.bind_param(stmt, 5, weather_main)
                ibm_db.bind_param(stmt, 6, weather_description)
                ibm_db.bind_param(stmt, 7, main_temp)
                ibm_db.bind_param(stmt, 8, main_temp_min)
                ibm_db.bind_param(stmt, 9, main_temp_max)
                ibm_db.bind_param(stmt, 10, wind_speed)
                ibm_db.bind_param(stmt, 11, wind_deg)
                ibm_db.bind_param(stmt, 12, wind_direction)
                ibm_db.bind_param(stmt, 13, dt_unix)
                ibm_db.bind_param(stmt, 14, timezone)
                ibm_db.bind_param(stmt, 15, current_date_wlg)
                ibm_db.bind_param(stmt, 16, current_time_wlg)
                ibm_db.bind_param(stmt, 17, current_date_mid)
                ibm_db.bind_param(stmt, 18, current_time_mid)
                ibm_db.bind_param(stmt, 19, user_id)
                print('Preparativos listos.')
                try:
                    ibm_db.execute(stmt)
                    result = True
                    print('Los datos fueron agregados a la DB')
                except:
                    print('Error en execute.')
                    print(ibm_db.stmt_errormsg())
            else:
                print('Error en la conexión a la DB.')
        else:
            print(request.status_code)
    except:
        print(ibm_db.stmt_errormsg())
    finally:
        request.close()
        if ibm_db.active(conn):
            ibm_db.close(conn)
            if ibm_db.active(conn) == False:
                print('La conexion a la base de datos se ha cerrado.')
        print('La conexion con el servidor de datos de Weather se ha cerrado.')
    return result
Exemple #18
0
import ibm_db

conn = ibm_db.connect(
    "DATABASE=DBNAME;HOSTNAME=192.168.1.220;PORT=50002;PROTOCOL=TCPIP;UID=admin;PWD=pass12345",
    '', '')
connState = ibm_db.active(conn)

print(connState)
Exemple #19
0
import config
import ibm_db
from itoolkit.db2.idb2call import *
conn = ibm_db.connect(config.database, config.user, config.password)
if ibm_db.active(conn):
    config.itransport = iDB2Call(conn)
else:
    raise Exception("db2 conn failed: " + ibm_db.conn_errormsg)