コード例 #1
0
def init_table(schema,
               name,
               ddl,
               cursor,
               drop=False,
               like=False,
               truncate=True):
    if drop:
        try:
            cursor.execute("DROP TABLE {s}.{t}".format(s=schema, t=name))
        except Exception as e:
            if ibm_db.stmt_error() != '42S02':
                logger.error("Could not drop table", name)
                raise e
    try:
        if like:
            cursor.execute("CREATE TABLE {s}.{t} AS ({d}) WITH NO DATA \
                            IN TS_PD_DATA_001".format(s=schema, t=name, d=ddl))
        else:
            cursor.execute(
                "CREATE TABLE {s}.{t} ({d}) IN TS_PD_DATA_001".format(s=schema,
                                                                      t=name,
                                                                      d=ddl))
    except Exception as e:
        if (not (ibm_db.stmt_error() == '42S01' and not drop)):
            raise e

    if (not drop and truncate):
        cursor.execute("TRUNCATE TABLE {s}.{t} IMMEDIATE".format(s=schema,
                                                                 t=name))
コード例 #2
0
    def run_test_133(self):
        conn = ibm_db.connect(config.database, config.user, config.password)

        if (not conn):
            print("Connection failed.")
            return 0

        ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)

        print("Starting test ...")
        res = ''
        sql = "INSERT INTO animals (id, breed, name, weight) VALUES (?, ?, ?, ?)"
        try:
            stmt = ibm_db.prepare(conn, sql)
            res = ibm_db.execute(
                stmt, (128, 'hacker of human and technological nature',
                       'Wez the ruler of all things PECL', 88.3))

            stmt = ibm_db.prepare(
                conn, "SELECT breed, name FROM animals WHERE id = ?")
            res = ibm_db.execute(stmt, (128, ))
            row = ibm_db.fetch_assoc(stmt)

            for i in row:
                print(i)

            ibm_db.rollback(conn)
            print("Done")
        except:
            print("SQLSTATE: %s" % ibm_db.stmt_error(stmt))
            print("Message: %s" % ibm_db.stmt_errormsg(stmt))

        try:
            stmt = ibm_db.prepare(
                conn, "SELECT breed, name FROM animals WHERE id = ?")
            res = ibm_db.execute(stmt, (128, ))
            row = ibm_db.fetch_assoc(stmt)
            if (row):
                for i in row:
                    print(i)
            print(res)
            print("SQLSTATE: %s" % ibm_db.stmt_error(stmt))
            print("Message: %s" % ibm_db.stmt_errormsg(stmt))
        except:
            print("An Exception is not expected")
            print("SQLSTATE: %s" % ibm_db.stmt_error(stmt))
            print("Message: %s" % ibm_db.stmt_errormsg(stmt))

        ibm_db.rollback(conn)
        print("Done")
コード例 #3
0
ファイル: InsuranceDB2Util.py プロジェクト: lrxcy/pyhive-1
def init_table(schema,
               name,
               ddl,
               con,
               drop=False,
               like=False,
               truncate=True,
               part_keys=None):
    cursor = con.cursor()

    logger.debug("Initing table {s}.{n} with options: "
                 "drop={d}, like={l}, truncate={t}".format(s=schema,
                                                           n=name,
                                                           d=drop,
                                                           l=like,
                                                           t=truncate))

    if drop:
        try:
            cursor.execute("DROP TABLE {s}.{t}".format(s=schema, t=name))
        except Exception as e:
            if ibm_db.stmt_error() != '42S02':
                logger.error("Could not drop table", name)
                raise e

    if part_keys:
        part_keys_sql = "DISTRIBUTE BY HASH (" + ",".join(part_keys) + ")"
    else:
        part_keys_sql = ''

    try:
        if like:
            cursor.execute("CREATE TABLE {s}.{t} AS ({d}) WITH NO DATA \
                            IN TS_PD_DATA_001 {pk}".format(s=schema,
                                                           t=name,
                                                           d=ddl,
                                                           pk=part_keys_sql))
        else:
            cursor.execute(
                "CREATE TABLE {s}.{t} ({d}) IN TS_PD_DATA_001 {pk}".format(
                    s=schema, t=name, d=ddl, pk=part_keys_sql))
    except Exception as e:
        if (not (ibm_db.stmt_error() == '42S01' and not drop)):
            raise e

    if (not drop and truncate):
        cursor.execute("TRUNCATE TABLE {s}.{t} IMMEDIATE".format(s=schema,
                                                                 t=name))
    cursor.close()
    def run_test_157a(self):
        conn = ibm_db.connect(config.database, config.user, config.password)
        server = ibm_db.server_info(conn)

        print("Starting...")
        if conn:
            sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed"
            result = ibm_db.exec_immediate(conn, sql)

            try:
                i = 2
                row = ibm_db.fetch_assoc(result, i)
                while (row):
                    if (server.DBMS_NAME[0:3] == 'IDS'):
                        print("%-5d %-16s %-32s %10s" %
                              (row['id'], row['name'], row['breed'],
                               row['weight']))
                    else:
                        print("%-5d %-16s %-32s %10s" %
                              (row['ID'], row['NAME'], row['BREED'],
                               row['WEIGHT']))
                    i = i + 2
                row = ibm_db.fetch_assoc(result, i)
            except:
                print("SQLSTATE: %s" % ibm_db.stmt_error(result))
                print("Message: %s" % ibm_db.stmt_errormsg(result))

            print("DONE")
コード例 #5
0
    def run_test_6561(self):
        conn = ibm_db.connect(config.database, config.user, config.password)

        if conn:
            ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)

            stmt = ibm_db.exec_immediate(
                conn,
                "INSERT INTO animals (id, breed, name, weight) VALUES (null, null, null, null)"
            )
            statement = "SELECT count(id) FROM animals"
            result = ibm_db.exec_immediate(conn, statement)
            if ((not result) and ibm_db.stmt_error()):
                print("ERROR: %s" % (ibm_db.stmt_errormsg(), ))

            row = ibm_db.fetch_tuple(result)
            while (row):
                for i in row:
                    print(i)
                row = ibm_db.fetch_tuple(result)

            ibm_db.rollback(conn)
            ibm_db.close(conn)

        else:
            print("Connection failed.")
コード例 #6
0
  def run_test_133(self):
    conn = ibm_db.connect(config.database, config.user, config.password)

    if (not conn):
      print "Connection failed."
      return 0

    ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)

    print "Starting test ..."
    res = ''
    sql =  "INSERT INTO animals (id, breed, name, weight) VALUES (?, ?, ?, ?)"
    try:
      stmt = ibm_db.prepare(conn, sql)
      res = ibm_db.execute(stmt,(128, 'hacker of human and technological nature', 'Wez the ruler of all things PECL', 88.3))
      
      stmt = ibm_db.prepare(conn, "SELECT breed, name FROM animals WHERE id = ?")
      res = ibm_db.execute(stmt, (128,))
      row = ibm_db.fetch_assoc(stmt)
      
      for i in row:
	         print i

      ibm_db.rollback(conn)
      print "Done"
    except:
      print "SQLSTATE: %s" % ibm_db.stmt_error(stmt)
      print "Message: %s" % ibm_db.stmt_errormsg(stmt)

    try:
        stmt = ibm_db.prepare(conn, "SELECT breed, name FROM animals WHERE id = ?")
        res = ibm_db.execute(stmt, (128,))
        row = ibm_db.fetch_assoc(stmt)
        if (row):
            for i in row:
                print i
        print res
        print "SQLSTATE: %s" % ibm_db.stmt_error(stmt)
        print "Message: %s" % ibm_db.stmt_errormsg(stmt)
    except:
        print "An Exception is not expected"
        print "SQLSTATE: %s" % ibm_db.stmt_error(stmt)
        print "Message: %s" % ibm_db.stmt_errormsg(stmt)

    ibm_db.rollback(conn)
    print "Done"
コード例 #7
0
ファイル: utils.py プロジェクト: gokycat/ibm-db
    def insert_many_records(self, recordslist, commitnum, tablename=None):
        conn = self.get_conn()
        for i in xrange(0, len(recordslist), commitnum):
            time.sleep(0.05)
            if tablename is None:
                import random

                tbname = 'xxx%d' % (random.randint(1, 5))
            else:
                tbname = tablename
            insertsql = "insert into %s(...) values(?, ?, ?, ?, ?, ?, \
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \
                    ?, ?, ?, ?)" % tbname
            try:
                stmt = ibm_db.prepare(conn, insertsql)
                ibm_db.execute_many(stmt, tuple(recordslist[i:i + commitnum]))
            except:
                print ibm_db.stmt_error(), ibm_db.stmt_errormsg()
            finally:
                ibm_db.commit(conn)
コード例 #8
0
def immediateOper(connection, sql, outFile):
    outFile.write("Performing immediate operation: {} \n".format(sql))
    stmt = None
    try:
        stmt = ibm_db.exec_immediate(connection, sql)
    except:
        outFile.write(ibm_db.stmt_error())
        outFile.write(ibm_db.stmt_errormsg())
        raise
    if not stmt:
        outFile.write("Operation FAILED \n")
    return stmt
コード例 #9
0
def consultaDB2(sql, conn):
    try:
        stmt = ibm_db.exec_immediate(conn, sql)
    except:
        print('Code SQL with problem!\nError Code: {0}'.format(
            ibm_db.stmt_error()))
        sys.exit()

    #print('Number of Fields: {0}'.format(ibm_db.num_fields(stmt)))

    print('Number of rows deleted, inserted, or updated: {0}'.format(
        ibm_db.num_rows(stmt)))

    return stmt
コード例 #10
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()
コード例 #11
0
 def save_dict_into_ibmdb(self, processor_type, data):
     if not isinstance(data, dict):
         return
     table = data.pop('table')
     # 贷款银行合同号解析
     if table in base_config.table_dict.keys():
         if data.get(base_config.table_dict.get(table).get(
                 'contractcode')) and data.get(
                     base_config.table_dict.get(table).get(
                         'orgname')) == '******':
             data[base_config.table_dict.get(table).get(
                 'orgname')] = filter_organization_code(
                     data.get(
                         base_config.table_dict.get(table).get(
                             'contractcode')),
                     data.get(
                         base_config.table_dict.get(table).get('date')))
     # 银票号解析
     elif table in base_config.draft_dict.keys():
         if data.get(base_config.draft_dict.get(table).get(
                 'contractcode')) and data.get(
                     base_config.draft_dict.get(table).get(
                         'orgname')) == '******':
             data[base_config.draft_dict.get(table).get(
                 'orgname')] = draft_filter(
                     data.get(
                         base_config.draft_dict.get(table).get(
                             'contractcode')))
     placeholders = ','.join(['?'] * len(data))
     columns = ','.join(data.keys())
     statement = "INSERT INTO {}.{}({}) VALUES({})".format(
         base_config.tabschema, table, columns, placeholders)
     # debug
     logger.info('processor_type:[{}], sql:[{} {}]'.format(
         processor_type, statement, tuple(data.values())))
     try:
         stmt = ibm_db.prepare(self.conn, statement)
         ibm_db.execute(stmt, tuple(data.values()))
     except:
         print('error state code:{}'.format(ibm_db.stmt_error()))
コード例 #12
0
ファイル: drop_table.py プロジェクト: mentu/juven_python
 def delete_all_table_data(self):
     query_tables_sql = "select trim(tabschema) as tabschema, tabname FROM syscat.tables WHERE tabschema = '{}'".format(
       tabschema.upper() or user.upper())
     result_query = ibm_db.exec_immediate(self.conn, query_tables_sql)
     row = ibm_db.fetch_assoc(result_query)
     while (row):
         if row.get('TABNAME').startswith("RH_") and row.get('TABNAME') not in  ['RH_CUST_QUEUE','RH_ERROR_SPIDER','RH_SPIDER_QUEUE_LIST']:
             # delete_sql = "truncate table {TABSCHEMA}.{TABNAME} immediate;".format(**row)
             # print(delete_sql)
             sql_delete = "delete from {TABSCHEMA}.{TABNAME} where  ='1101000002264820'".format(**row)
             print(sql_delete)
             # delete_sql2 = "delete from {TABSCHEMA}.{TABNAME} where MIDSIGNCODE='3309060000195576' and date(uploadtime)='2016-12-15';".format(**row)
             # print(delete_sql2)
             try:
                 # ibm_db.exec_immediate(self.conn, sql_delete)
                 ibm_db.exec_immediate(self.conn, sql_delete)
                 # ibm_db.exec_immediate(self.conn, delete_sql2)
             except Exception as e:
                 print('error state code:{}'.format(ibm_db.stmt_error()),"error state=",e)
             # time.sleep(0.1)
         row = ibm_db.fetch_assoc(result_query)
         ibm_db.commit(self.conn)
コード例 #13
0
    def execute_query(self, query: str, bind_vars: Any) -> Tuple[List, List]:
        """
        Execute query at DB2 Database via connection

        Args:
            query(str): db2 query string
            bind_vars(Any): in case there are names and values - a bind_vars dict,
                            in case there are only values - list

        Returns:
            Tuple[results(List), headers(List)]
        """
        results = list()
        headers = list()
        status = False

        stmt = self._prepare_statement(query, bind_vars)

        try:
            demisto.info("Executing ...")
            status = ibm_db.execute(stmt)
            demisto.info("Done !!!")
        except Exception:
            demisto.error(clear(ibm_db.stmt_error()))
            demisto.error(clear(ibm_db.stmt_errormsg()))
            raise DemistoException(clear(ibm_db.stmt_errormsg()))

        demisto.info("Collecting results")
        if status:
            row = ibm_db.fetch_assoc(stmt)
            while row:
                results.append(row)
                row = ibm_db.fetch_assoc(stmt)

        if results:
            headers = [*results[0]]

        return results, headers
コード例 #14
0
 def retrieve_and_store(self):
     global global_fifo_q
     while True:
         if not global_fifo_q.empty():
             #Check for active connection
             data_from_q = global_fifo_q.get()
             #Format datatime
             db2_datetime = data_from_q[1].strftime('%Y-%m-%d-%H.%M.%S.%f')
             #print (db2_datetime)
             #print(data_from_q)
             try:
                 stmt = ibm_db.prepare(
                     self.dbconn,
                     "insert into mrj3017.python_test1 (col1, col2, col3) values (?,?,?)"
                 )
                 ibm_db.execute(stmt, (
                     data_from_q[0],
                     db2_datetime,
                     data_from_q[2],
                 ))
             except:
                 print("Transaction couldn't be completed:")
                 print(ibm_db.stmt_errormsg())
                 print(ibm_db.stmt_error())
                 if (ibm_db.conn_error()):
                     print("conn_error, will retry after 5 seconds:")
                     print(ibm_db.conn_error())
                     while True:
                         time.sleep(5)
                         try:
                             self.dbconn = ibm_db.connect(
                                 self.target_db, self.db_user, self.db_pass)
                             if (self.dbconn):
                                 print("Connection reconnected to :" +
                                       self.target_db)
                                 break
                         except:
                             print("NO connection to :" + self.target_db)
コード例 #15
0
  def run_test_6561(self):
    conn = ibm_db.connect(config.database, config.user, config.password)
    
    if conn:
      ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)

      stmt = ibm_db.exec_immediate(conn, "INSERT INTO animals (id, breed, name, weight) VALUES (null, null, null, null)")
      statement = "SELECT count(id) FROM animals"
      result = ibm_db.exec_immediate(conn, statement)
      if ( (not result) and ibm_db.stmt_error() ):
        print("ERROR: %s" % (ibm_db.stmt_errormsg(), ))

      row = ibm_db.fetch_tuple(result)
      while ( row ):
        for i in row:
            print(i)
        row = ibm_db.fetch_tuple(result)
    
      ibm_db.rollback(conn)
      ibm_db.close(conn)
      
    else:
      print("Connection failed.")
  def run_test_157a(self):
    conn = ibm_db.connect(config.database, config.user, config.password)
    server = ibm_db.server_info( conn )

    print "Starting..."
    if conn:
      sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed"
      result = ibm_db.exec_immediate(conn, sql)

      try:
          i = 2
          row = ibm_db.fetch_assoc(result, i)
          while ( row ):
              if (server.DBMS_NAME[0:3] == 'IDS'):
                print "%-5d %-16s %-32s %10s" % (row['id'], row['name'], row['breed'], row['weight'])
              else:
                print "%-5d %-16s %-32s %10s" % (row['ID'], row['NAME'], row['BREED'], row['WEIGHT'])
              i = i + 2
          row = ibm_db.fetch_assoc(result, i)
      except:
          print "SQLSTATE: %s" % ibm_db.stmt_error(result)
          print "Message: %s" % ibm_db.stmt_errormsg(result)
	
      print "DONE"
コード例 #17
0
if conn.returnCode is True:
    dbConnection = conn.connectionID
else:
    conn.closeConnection()
    exit(-1)

# Execute The SQL Statement Specified
print("Executing the SQL statement specified ... ", end="")
try:
    resultSet = ibm_db.exec_immediate(dbConnection, sqlStatement)
except Exception:
    pass

# If The SQL Statement Could Not Be Executed, Display An Error Message And Exit
if resultSet is False:
    print("\nERROR: Unable to execute the SQL statement.")
    errorCode = ibm_db.stmt_error()
    print("\nSQLSTATE: " + errorCode + "\n")
    conn.closeConnection()
    exit(-1)

# Otherwise, Complete The Status Message
else:
    print("Done!\n")

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

# Return Control To The Operating System
exit()
コード例 #18
0
  def run_test_133(self):
    conn = ibm_db.connect(config.database, config.user, config.password)

    if (not conn):
      print("Connection failed.")
      return 0

    ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)

    print("Starting test ...")
    res = ''
    sql =  "INSERT INTO animals (id, breed, name, weight) VALUES (?, ?, ?, ?)"
    try:
      stmt = ibm_db.prepare(conn, sql)
      res = ibm_db.execute(stmt,(128, 'hacker of human and technological nature', 'Wez the ruler of all things PECL', 88.3))
      
      stmt = ibm_db.prepare(conn, "SELECT breed, name FROM animals WHERE id = ?")
      res = ibm_db.execute(stmt, (128,))
      row = ibm_db.fetch_assoc(stmt)
      
      for i in row:
	         print(i)

      ibm_db.rollback(conn)
      print("Done")
    except:
      print("SQLSTATE: %s" % ibm_db.stmt_error(stmt))
      print("Message: %s" % ibm_db.stmt_errormsg(stmt))

    try:
        stmt = ibm_db.prepare(conn, "SELECT breed, name FROM animals WHERE id = ?")
        res = ibm_db.execute(stmt, (128,))
        row = ibm_db.fetch_assoc(stmt)
        if (row):
            for i in row:
                print(i)
        print(res)
        print("SQLSTATE: %s" % ibm_db.stmt_error(stmt))
        print("Message: %s" % ibm_db.stmt_errormsg(stmt))
    except:
        print("An Exception is not expected")
        print("SQLSTATE: %s" % ibm_db.stmt_error(stmt))
        print("Message: %s" % ibm_db.stmt_errormsg(stmt))

    ibm_db.rollback(conn)
    print("Done")

#__END__
#__LUW_EXPECTED__
#Starting test ...
#
#SQLSTATE: 22001
#Message: [IBM][CLI Driver] CLI0109E  String data right truncation. SQLSTATE=22001 SQLCODE=-99999
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][DB2/%s] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000 SQLCODE=100
#Done
#__ZOS_EXPECTED__
#Starting test ...
#
#SQLSTATE: 22001
#Message: [IBM][CLI Driver] CLI0109E  String data right truncation. SQLSTATE=22001 SQLCODE=-99999
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][DB2] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000 SQLCODE=100
#Done
#__SYSTEMI_EXPECTED__
#Starting test ...
#
#SQLSTATE: 22001
#Message: [IBM][CLI Driver] CLI0109E  String data right truncation. SQLSTATE=22001 SQLCODE=-99999
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][AS] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000 SQLCODE=100
#Done
#__IDS_EXPECTED__
#Starting test ...
#
#SQLSTATE: 22001
#Message: [IBM][CLI Driver][IDS%s] Value exceeds string column length. SQLCODE=-1279
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][IDS%s] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000 SQLCODE=100
#Done
コード例 #19
0
            schema2 = schema1
        conn2 = get_connection(dbname2, hostname2, port2, userid2, password2)

        if args.output_file:
            fout = open(args.output_file, 'w')
        else:
            fout = sys.stdout
        print_legend(args.hostname1, hostname2)
        # Compare DNs/ModifyTimestamp from first and second LDAP servers
        compare_all_entry_modify_timestamps(args.hostname1, conn1, schema1, hostname2, conn2, schema2, fout)
        endtime = datetime.utcnow()
        logger.info("End of Script: {}".format(endtime))
        print("Script ran for: {}".format(endtime - starttime))
    except Exception as e:
        conn_error = ibm_db.conn_error()
        stmt_error = ibm_db.stmt_error()
        if conn_error != '':
            print("Error Code: {} Msg: {}".format(conn_error, ibm_db.conn_errormsg()))
            if conn1:
                print("Connection issue with server#2 most probably.")
            else:
                print("Connection issue with server#1 most probably.")
        elif stmt_error != '':
            print("Error Code: {} Msg: {}".format(stmt_error, ibm_db.stmt_errormsg()))
        raise e
    finally:
        if fout and fout is not sys.stdout:
            fout.close()
        if conn1:
            ibm_db.close(conn1)
        if conn2:
コード例 #20
0
ファイル: ibm_db_v1.py プロジェクト: sxkundu/junk
def run_sql(db_name):
    global global_fifo_q
    str = open('C:/Users/sxk11/PycharmProjects/Safari_1/test.txt', 'r').read()
    #print (db_name)
    try:
        conn = ibm_db.connect(db_name, 'tu01945', str)
    except:
        print("NO connection to :" + db_name)
        #print(ibm_db.stmt_errormsg())
        #print(ibm_db.stmt_error())
        if (ibm_db.conn_error()):
            print("conn_error:")
            print(ibm_db.conn_error())
            while True:
                time.sleep(5)
                try:
                    conn = ibm_db.connect(db_name, 'tu01945', str)
                    if (conn):
                        print("Connection reconnected to :" + db_name)
                        break
                except:
                    print("NO connection to :" + db_name)

            #Send Notification
            #Retry
    else:
        print("The connection to " + db_name + " was successful!")
        #print (conn)

    sql = 'select snapshot_timestamp, db_name, catalog_partition  from sysibmadm.snapdb'

    #time.sleep(30)

    while True:
        try:
            stmt = ibm_db.exec_immediate(conn, sql)
            #stmt = ibm_db.prepare(conn, sql)
            #ibm_db.execute(stmt)
        except:

            print("Transaction couldn't be completed:")
            print(ibm_db.stmt_errormsg())
            print(ibm_db.stmt_error())
            if (ibm_db.conn_error()):
                print("conn_error:")
                print(ibm_db.conn_error())
                while True:
                    time.sleep(5)
                    try:
                        conn = ibm_db.connect(db_name, 'tu01945', str)
                        if (conn):
                            print("Connection reconnected to :" + db_name)
                            break
                    except:
                        print("NO connection to :" + db_name)

        else:
            tuple = ibm_db.fetch_tuple(stmt)
            while tuple != False:
                #print("The time is : ", tuple[0])
                #print("The catalog name is : ", tuple[1])
                #print("The catalog partition is : ", tuple[2])
                #Store Data in queue
                data = (tuple[1], tuple[0], tuple[2])
                global_fifo_q.put(data)
                #Get next
                tuple = ibm_db.fetch_tuple(stmt)
                time.sleep(10)
コード例 #21
0
  def run_test_133(self):
    conn = ibm_db.connect(config.database, config.user, config.password)

    if (not conn):
      print "Connection failed."
      return 0

    ibm_db.autocommit(conn, ibm_db.SQL_AUTOCOMMIT_OFF)

    print "Starting test ..."
    res = ''
    sql =  "INSERT INTO animals (id, breed, name, weight) VALUES (?, ?, ?, ?)"
    try:
      stmt = ibm_db.prepare(conn, sql)
      res = ibm_db.execute(stmt,(128, 'hacker of human and technological nature', 'Wez the ruler of all things PECL', 88.3))
      
      stmt = ibm_db.prepare(conn, "SELECT breed, name FROM animals WHERE id = ?")
      res = ibm_db.execute(stmt, (128,))
      row = ibm_db.fetch_assoc(stmt)
      
      for i in row:
	         print i

      ibm_db.rollback(conn)
      print "Done"
    except:
      print "SQLSTATE: %s" % ibm_db.stmt_error(stmt)
      print "Message: %s" % ibm_db.stmt_errormsg(stmt)

    try:
        stmt = ibm_db.prepare(conn, "SELECT breed, name FROM animals WHERE id = ?")
        res = ibm_db.execute(stmt, (128,))
        row = ibm_db.fetch_assoc(stmt)
        if (row):
            for i in row:
                print i
        print res
        print "SQLSTATE: %s" % ibm_db.stmt_error(stmt)
        print "Message: %s" % ibm_db.stmt_errormsg(stmt)
    except:
        print "An Exception is not expected"
        print "SQLSTATE: %s" % ibm_db.stmt_error(stmt)
        print "Message: %s" % ibm_db.stmt_errormsg(stmt)

    ibm_db.rollback(conn)
    print "Done"

#__END__
#__LUW_EXPECTED__
#Starting test ...
#None
#SQLSTATE: 22001
#Message: [IBM][CLI Driver] CLI0109E  String data right truncation. SQLSTATE=22001 SQLCODE=-99999
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][DB2%s] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000
#Done
#__ZOS_EXPECTED__
#Starting test ...
#
#SQLSTATE: 22001
#Message: [IBM][CLI Driver] CLI0109E  String data right truncation. SQLSTATE=22001 SQLCODE=-99999
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][DB2] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000 SQLCODE=100
#Done
#__SYSTEMI_EXPECTED__
#Starting test ...
#
#SQLSTATE: 22001
#Message: [IBM][CLI Driver] CLI0109E  String data right truncation. SQLSTATE=22001 SQLCODE=-99999
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][AS] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000 SQLCODE=100
#Done
#__IDS_EXPECTED__
#Starting test ...
#None
#SQLSTATE: 22001
#Message: [IBM][CLI Driver][IDS%s] Value exceeds string column length.
#True
#SQLSTATE: 02000
#Message: [IBM][CLI Driver][IDS%s] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000
#Done