python类connect()的实例源码

Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = psycopg2.connect(
                self.GetConnectionString(),
                cursor_factory=psycopg2.extras.DictCursor
            )
            self.v_con.autocommit = p_autocommit
            self.v_cur = self.v_con.cursor()
            self.v_start = True
            # PostgreSQL types
            self.v_cur.execute('select oid, typname from pg_type')
            self.v_types = dict([(r['oid'], r['typname']) for r in self.v_cur.fetchall()])
            if not p_autocommit:
                self.v_con.commit()
            self.v_con.notices = DataList()
        except Spartacus.Database.Exception as exc:
            raise exc
        except psycopg2.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
checkmesft.py 文件源码 项目:wechat_oms 作者: bsbforever 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def oraclesql():
    ipaddress='10.65.1.120'
    username='sys'
    password='ase_sys_n'
    port='1521'
    tnsname='dctest'
    try:
        db = cx_Oracle.connect(username+'/'+password+'@'+ipaddress+':'+port+'/'+tnsname ,mode=cx_Oracle.SYSDBA)
    except Exception as e:
        content= (tnsname+' is Unreachable,The reason is '+ str(e)).strip()
        print (content)
    else:
        cursor = db.cursor()
        data=oraclesql(cursor)
        cursor.close()
        db.close()

    cursor.execute('select max(count(*))  from v$open_cursor group by sid')
    data=cursor.fetchone()
    return data
oracle_hook.py 文件源码 项目:incubator-airflow-old 作者: apache 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_conn(self):
        """
        Returns a oracle connection object
        Optional parameters for using a custom DSN connection (instead of using a server alias from tnsnames.ora)
        The dsn (data source name) is the TNS entry (from the Oracle names server or tnsnames.ora file)
        or is a string like the one returned from makedsn().

        :param dsn: the host address for the Oracle server
        :param service_name: the db_unique_name of the database that you are connecting to (CONNECT_DATA part of TNS)
        You can set these parameters in the extra fields of your connection
        as in ``{ "dsn":"some.host.address" , "service_name":"some.service.name" }``
        """
        conn = self.get_connection(self.oracle_conn_id)
        dsn = conn.extra_dejson.get('dsn', None)
        sid = conn.extra_dejson.get('sid', None)
        mod = conn.extra_dejson.get('module', None)

        service_name = conn.extra_dejson.get('service_name', None)
        if dsn and sid and not service_name:
            dsn = cx_Oracle.makedsn(dsn, conn.port, sid)
            conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
        elif dsn and service_name and not sid:
            dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name)
            conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
        else:
            conn = cx_Oracle.connect(conn.login, conn.password, conn.host)

        if mod is not None:
            conn.module = mod

        return conn
connector.py 文件源码 项目:autoinjection 作者: ChengWiLL 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def connect(self):
        self.initConnection()
        self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
        self.__dsn = utf8encode(self.__dsn)
        self.user = utf8encode(self.user)
        self.password = utf8encode(self.password)

        try:
            self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
            logger.info("successfully connected as SYSDBA")
        except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
            try:
                self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
            except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
                raise SqlmapConnectionException(msg)

        self.initCursor()
        self.printConnected()
oracledb.py 文件源码 项目:internet-content-detection 作者: liubo0621 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, ip = IP, port = PORT, db = DB, user_name = USER_NAME, user_pass = USER_PASS):
        super(OracleDB, self).__init__()

        if STOP_ORCL:
            return

        if not hasattr(self,'conn'):
            try:
                self.conn = cx_Oracle.connect(user_name, user_pass, '%s:%d/%s'%(ip, port, db))#, threaded=True,events = True)
                self.cursor = self.conn.cursor()
            except Exception as e:
                raise
            else:
                log.debug('?????? %s'%db)
play_common.py 文件源码 项目:ansibleProject 作者: waitig 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_connect(self):
        db = cx_Oracle.connect(self.username, self.password, self.host_string)

        # print db.version
        # versioning = db.version.split('.')
        # if versioning[0] == '10':
        #     print "Running 10g"
        # elif versioning[0] == '9':
        #     print "Running 9i"
        # print db.dsn

        # sql = 'SELECT * FROM' + self.table_name
        # # cursor.execute('SELECT * FROM %s',str)
        # cursor.execute(sql)
        # # pprint(cursor.fetchall())
        #
        # # for row in cursor:  ## notice that this is plain English!
        # #     print row
        #
        # column_data_types = cursor.execute('SELECT * FROM ADP_D_HOST')
        #
        # print column_data_types
        #
        # pprint(cursor.description)
        return db.cursor()
connector.py 文件源码 项目:Eagle 作者: magerx 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def connect(self):
        self.initConnection()
        self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
        self.__dsn = utf8encode(self.__dsn)
        self.user = utf8encode(self.user)
        self.password = utf8encode(self.password)

        try:
            self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
            logger.info("successfully connected as SYSDBA")
        except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
            try:
                self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
            except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
                raise SqlmapConnectionException(msg)

        self.initCursor()
        self.printConnected()
connector.py 文件源码 项目:Helix 作者: 3lackrush 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def connect(self):
        self.initConnection()
        self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
        self.__dsn = utf8encode(self.__dsn)
        self.user = utf8encode(self.user)
        self.password = utf8encode(self.password)

        try:
            self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
            logger.info("successfully connected as SYSDBA")
        except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
            try:
                self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
            except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
                raise SqlmapConnectionException(msg)

        self.initCursor()
        self.printConnected()
connector.py 文件源码 项目:autoscan 作者: b01u 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def connect(self):
        self.initConnection()
        self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
        self.__dsn = utf8encode(self.__dsn)
        self.user = utf8encode(self.user)
        self.password = utf8encode(self.password)

        try:
            self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
            logger.info("successfully connected as SYSDBA")
        except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
            try:
                self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
            except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
                raise SqlmapConnectionException(msg)

        self.initCursor()
        self.printConnected()
oracle_hook.py 文件源码 项目:airflow 作者: apache-airflow 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_conn(self):
        """
        Returns a oracle connection object
        Optional parameters for using a custom DSN connection (instead of using a server alias from tnsnames.ora)
        The dsn (data source name) is the TNS entry (from the Oracle names server or tnsnames.ora file)
        or is a string like the one returned from makedsn().
        :param dsn: the host address for the Oracle server
        :param service_name: the db_unique_name of the database that you are connecting to (CONNECT_DATA part of TNS)
        You can set these parameters in the extra fields of your connection
        as in ``{ "dsn":"some.host.address" , "service_name":"some.service.name" }``
        """
        conn = self.get_connection(self.oracle_conn_id)
        dsn = conn.extra_dejson.get('dsn', None)
        sid = conn.extra_dejson.get('sid', None)
        service_name = conn.extra_dejson.get('service_name', None)
        if dsn and sid and not service_name:
            dsn = cx_Oracle.makedsn(dsn, conn.port, sid)
            conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
        elif dsn and service_name and not sid:
            dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name)
            conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
        else:
            conn = cx_Oracle.connect(conn.login, conn.password, conn.host)
        return conn
get_sms_code.py 文件源码 项目:python 作者: zhouyuyan 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def oracle_connect(self, mobile):
        # ??????
        t = time.strftime('%Y%m%d', time.localtime(time.time()))
        # ??oracle????????
        conn = cx_Oracle.connect('???/??')
        cursor = conn.cursor()
        # ?????SQL???????
        sql = r"select * from (select sms_inf from gwadm.SMSTSMmO where mbl_no = " + "'" + mobile + "'" + " and tx_dt = " + t + " order by OPR_TM desc)where rownum <= 1"
        cursor.execute(sql)
        row = cursor.fetchone()
        cursor.close()
        conn.close()
        code = []
        # ??????????
        for i in row[0]:
            if i.isdigit():
                code.append(i)
        return ''.join(code)
oracle_connect.py 文件源码 项目:Python-Quant 作者: saberxxy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def connect(username='stock', password='123456', host='localhost', port=1521, sid='orcl'):
    # tns = cx_Oracle.makedsn(host, port, sid)
    # con = cx_Oracle.connect(username, password, tns)  # ?????
    # cursor = conn.cursor()  # ??cursor
    # return cursor
    cf = configparser.ConfigParser()
    cf.read("..\\config\\config.conf")
    oracleHost = str(cf.get("oracle", "ip"))
    oraclePort = int(cf.get("oracle", "port"))
    oracleUser = str(cf.get("oracle", "username"))
    oraclePassword = str(cf.get("oracle", "password"))
    oracleDatabaseName = str(cf.get("oracle", "databasename"))
    oracleConn = oracleUser + '/' + oraclePassword + '@' + oracleHost + '/' + oracleDatabaseName
    conn = cxo.connect(oracleConn)
    return conn


# ????????
recipe-576534.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def add_ver_info(separate_files, connect_string, username):
    """add version information"""
    f = None
    if separate_files:
        ver_file = os.path.join(SCHEMA_DIR, 'version.txt')
        f = open_file_write(ver_file)
    title = 'info'
    print_start_info(title)
    output_line('date: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), f)
    output_line('connect string: %s' % (connect_string), f)
    output_line('user: %s' % (username), f)
    script_ver = __version__[5:-2]
    output_line('created by: %s' % (script_ver), f)
    print_stop_info(title)
    show_qry('DB version', DB_VERSION_SQL, fout=f)
    show_qry('DB name', 'SELECT ora_database_name FROM dual', fout=f)
    sel_info_option = '--ver-info-sql'
    for s in sys.argv[1:]:
        if s.startswith(sel_info_option):
            sel = s[len(sel_info_option):].strip('=')
            try:
                show_qry(sel, sel, fout=f)
            except:
                ex_info = traceback.format_exc()
                serr = '\nSQL: %s\nException: %s\n' % (sel, ex_info)
                print_err(serr)
            break
    show_qry('DB features used', FEATURE_USAGE_SQL, fout=f)
    if f:
        f.close()
oraclefuz.py 文件源码 项目:darkc0de-old-stuff 作者: tuwid 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def fuzzData(data, index):
    global connection

    for x in funnydata:
        try:
            if type(x) is int:
                print "Data is number",x
            else:
                print "Data is " + str(x)[0:30] + " of length " + str(len(str(x)))

            varList = []

            for var in range(index):
                varList.append(x)

            cur = connection.cursor()
            cur.execute(data, varList)

        except:
            error = str(sys.exc_info()[1])

            if error.upper().find("ORA-00933") > -1 or error.upper().find("ORA-01756:") > -1 or error.upper().find("ORA-00923:") > -1:
                print "*** POSSIBLE SQL INJECTION FOUND ***"
            elif error.upper().find("ORA-03113") > -1:
                if len(str(x)) > 50:
                    print "*** POSSIBLE BUFFER OVERFLOW ***"
                else:
                    print "*** INSTANCE CRASHED ***"

                print "Reconnecting ... "
                connect()
            elif error.upper().find("ORA-00600") > -1:
                print "*** INTERNAL ERROR ***"
            elif error.upper().find("PLS-00306:") > -1:
                print "Currently unfuzzable :("
                continue
            elif error.upper().find("ORA-03114") > -1:
                print "We are not connected :?"
                connect()

            print error
base.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_new_connection(self, conn_params):
        conn_string = convert_unicode(self._connect_string())
        return Database.connect(conn_string, **conn_params)
finefeequery.py 文件源码 项目:autocirc 作者: cherveny 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def findTotal(patronID):
    # function to get the total amount of fines owed for a patron, not just the weekly fines
    # Does lookup based on patron id
    sum = 0.0;

    # make connection to the database
    dsn = cx_Oracle.makedsn("localhost","1521","VGER")
    con = cx_Oracle.connect(user="READ-ONLY-DBA-USER",password="READ-ONLY-DBA-PASS",dsn=dsn)
    cur = con.cursor()

    # run the query
    query = """
            SELECT sum(fine_fee_balance)
            FROM fine_fee
            WHERE patron_id='{pID}'
    """

    cur.execute(query.format(pID=patronID));

    try:
        sum = cur.fetchone()[0]
    except:
        sum  = 0.0

    return sum
autocirc.py 文件源码 项目:autocirc 作者: cherveny 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def findSSAN(patronID):
    # function to get a users SSAN (bannerID) based on patronID
    # returns String NONE if value is None (alumni users, etc)
    # added to allow for banner id to go in summary, as per TKT-193

    ssan = "NONE";

    # make connection to the database
    dsn = cx_Oracle.makedsn(db_host,db_port,db_SID)
    con = cx_Oracle.connect(user=db_user,password=db_password,dsn=dsn)
    cur = con.cursor()

    # run the query
    query = """
        SELECT
            pt.ssan
        FROM
            patron pt
        WHERE
            pt.patron_id IN ({pID})
    """
    cur.execute(query.format(pID=patronID));

    try:
        ssan    = cur.fetchone()[0]
    except:
        ssan = "NONE"


    if ssan == None:
        ssan = "NONE"
    else:
        ssan = "@" + ssan[1:]

    return ssan;
autocirc.py 文件源码 项目:autocirc 作者: cherveny 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def findItemType(barCode):
    # function to get the type of an item, based on itemId.
    # checks for temporary item ID being set, if so, returns that type instead
    # Note: dicts field itemId isn't really itemId, it's item barcode
    # dict's barcode field is PATRON barcode
    itemType = "NONE";

    # make connection to the database
    dsn = cx_Oracle.makedsn(db_host,db_port,db_SID)
    con = cx_Oracle.connect(user=db_user,password=db_password,dsn=dsn)
    cur = con.cursor()

    # run the query
    query = """
        SELECT
            itt.item_type_name
        FROM
            item it,
            item_type itt,
            item_barcode ib
        WHERE
            ib.item_barcode IN ('{itemNumber}') AND
            ib.item_id = it.item_id AND
            itt.item_type_id = CASE WHEN (it.temp_item_type_id = '0') THEN it.item_type_id ELSE it.temp_item_type_id END
    """

    cur.execute(query.format(itemNumber=barCode));

    try:
        itemType    = cur.fetchone()[0]
    except:
        itemType = "NONE"

    if itemType == None:
        itemType = "NONE"

    return itemType;

##########Utility Functions
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = sqlite3.connect(self.v_service, self.v_timeout)
            #self.v_con.row_factory = sqlite3.Row
            self.v_cur = self.v_con.cursor()
            if self.v_foreignkeys:
                self.v_cur.execute('PRAGMA foreign_keys = ON')
            self.v_start = True
        except sqlite3.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = sqlite3.connect(self.v_service, self.v_timeout)
            #self.v_con.row_factory = sqlite3.Row
            self.v_cur = self.v_con.cursor()
            if self.v_foreignkeys:
                self.v_cur.execute('PRAGMA foreign_keys = ON')
            self.v_start = True
        except sqlite3.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = pymysql.connect(
                host=self.v_host,
                port=int(self.v_port),
                db=self.v_service,
                user=self.v_user,
                password=self.v_password,
                cursorclass=pymysql.cursors.DictCursor)
            self.v_cur = self.v_con.cursor()
            self.v_start = True
        except pymysql.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = pymysql.connect(
                host=self.v_host,
                port=int(self.v_port),
                db=self.v_service,
                user=self.v_user,
                password=self.v_password,
                cursorclass=pymysql.cursors.DictCursor)
            self.v_cur = self.v_con.cursor()
            self.v_start = True
        except pymysql.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = cx_Oracle.connect('{0}/{1}@{2}:{3}/{4}'.format(
                self.v_user,
                self.v_password,
                self.v_host,
                self.v_port,
                self.v_service
            ))
            self.v_cur = self.v_con.cursor()
            self.v_start = True
        except cx_Oracle.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 56 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            self.v_con = pymssql.connect(
                host=self.v_host,
                port=int(self.v_port),
                database=self.v_service,
                user=self.v_user,
                password=self.v_password
            )
            self.v_cur = self.v_con.cursor()
            self.v_start = True
        except pymssql.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
Database.py 文件源码 项目:spartacus 作者: wind39 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def Open(self, p_autocommit=True):
        try:
            c = ibm_db.connect(self.GetConnectionString(), '', '')
            self.v_con = ibm_db_dbi.Connection(c)
            self.v_cur = self.v_con.cursor()
            self.v_start = True
        except ibm_db.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except ibm_db_dbi.Error as exc:
            raise Spartacus.Database.Exception(str(exc))
        except Exception as exc:
            raise Spartacus.Database.Exception(str(exc))
base.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_new_connection(self, conn_params):
        conn_string = convert_unicode(self._connect_string())
        return Database.connect(conn_string, **conn_params)
base.py 文件源码 项目:trydjango18 作者: wei0104 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_new_connection(self, conn_params):
        conn_string = convert_unicode(self._connect_string())
        return Database.connect(conn_string, **conn_params)
base.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_new_connection(self, conn_params):
        conn_string = convert_unicode(self._connect_string())
        return Database.connect(conn_string, **conn_params)
dal.py 文件源码 项目:qal 作者: OptimalBPM 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, _resource=None, _connect = True):
        """

        :param _resource: A resource object to read settings from
        :param _connect: Also connect to the database (default:True)
        """

        self.on_connect = None

        if _resource is not None:
            self.resource = _resource
            self.read_resource_settings(_resource)
            if _connect:
                self.connect_to_db()
ansiblerun.py 文件源码 项目:ansibleProject 作者: waitig 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def get_connect(self):
        db = cx_Oracle.connect(self.username, self.password, self.host_string)
        return db.cursor()


问题


面经


文章

微信
公众号

扫码关注公众号