当前位置: 首页>>代码示例>>Python>>正文


Python connector.Error方法代码示例

本文整理汇总了Python中mysql.connector.Error方法的典型用法代码示例。如果您正苦于以下问题:Python connector.Error方法的具体用法?Python connector.Error怎么用?Python connector.Error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mysql.connector的用法示例。


在下文中一共展示了connector.Error方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def get(self, query):
        try:
            rows = None
            with self.cursor() as cursor:
                cursor.execute(query)
                _rows = cursor.fetchall()
                if _rows:
                    rows = list()
                    for row in _rows:
                        rows.append(row)
                    if len(rows) == 1:
                        rows = rows[0]
                        if len(rows) == 1:
                            rows = rows[0]

            return rows
        except mysql.Error as e:
            msg = 'Failure in executing query {0}. Error: {1}'.format(query, e)
            raise DatabaseError(msg) 
开发者ID:RepoReapers,项目名称:reaper,代码行数:21,代码来源:database.py

示例2: add_connectivy_to_offerings

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def add_connectivy_to_offerings(self):
        """Add network offering to Cosmic with NSX connectivity"""
        cloud_cursor = self.cloud_db.cursor()
        try:
            cloud_cursor.execute(
                "INSERT IGNORE INTO cloud.network_offering_service_map (network_offering_id, service, provider, created) "
                "(SELECT DISTINCT X.network_offering_id, 'Connectivity', 'NiciraNvp', X.created FROM cloud.network_offering_service_map X);")
            cloud_cursor.execute(
                "INSERT IGNORE INTO cloud.vpc_offering_service_map (vpc_offering_id, service, provider, created) "
                "(SELECT DISTINCT X.vpc_offering_id, 'Connectivity', 'NiciraNvp', X.created FROM cloud.vpc_offering_service_map X);")
            cloud_cursor.execute(
                "INSERT IGNORE INTO cloud.network_offering_service_map (network_offering_id, service, provider, created) "
                "(SELECT DISTINCT X.id, 'Connectivity', 'NiciraNvp', X.created FROM cloud.network_offerings X "
                "WHERE name IN ('DefaultPrivateGatewayNetworkOffering', 'DefaultPrivateGatewayNetworkOfferingSpecifyVlan', 'DefaultSyncNetworkOffering'));")
        except Error as e:
            print("==> Error executing MariaDB query: ", e)
        finally:
            if self.cloud_db.is_connected():
                cloud_cursor.close() 
开发者ID:MissionCriticalCloud,项目名称:bubble-toolkit,代码行数:21,代码来源:NSX.py

示例3: __init__

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def __init__(self, user, password, database=None, verbose=LOG_OFF):
        # passwd = input("Password > ")
        # passwd = password
        self._v = verbose

        if database is not None:
            self.database = database
            try:
                self.conn = maria.connect(user=user, password=password, database=self.database)
            except maria.Error as err:
                if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                    print("Something is wrong with your user name or password")
                elif err.errno == errorcode.ER_BAD_DB_ERROR:
                    print("Database does not exist")
                else:
                    print(err)
        else:
            try:
                self.conn = maria.connect(user=user, password=password)
            except maria.Error as err:
                if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                    print("Something is wrong with your user name or password")
                else:
                    print(err) 
开发者ID:dfrc-korea,项目名称:carpe,代码行数:26,代码来源:mariadb.py

示例4: query

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def query(self, q, *args):
        cursor = self.conn.cursor()
        if not args:
            try:
                cursor.execute(q)
            except maria.Error as err:
                print("Failed query: {}".format(q))
                print(err)
                return False
        else:
            try:
                cursor.execute(q, tuple(v for v in args))
            except maria.Error as err:
                print("Failed query: {} {}".format(q, tuple(v for v in args)))
                print(err)
                return False

        self.conn.commit()
        return True 
开发者ID:dfrc-korea,项目名称:carpe,代码行数:21,代码来源:mariadb.py

示例5: wait_for_connection

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def wait_for_connection(self, user='root', password=None, database=None,
                            timeout=10):
        """
        Polls mysqld socket until we get a connection or the timeout
        expires (raise WaitTimeoutError). Defaults to root empty/password.
        """
        while timeout > 0:
            try:
                sock = '/var/run/mysqld/mysqld.sock'
                return mysqlconn.connect(unix_socket=sock,
                                         user=user,
                                         password=password,
                                         database=database,
                                         charset='utf8',
                                         connection_timeout=timeout)
            except MySQLError as ex:
                timeout = timeout - 1
                if timeout == 0:
                    raise WaitTimeoutError(ex)
                time.sleep(1) 
开发者ID:autopilotpattern,项目名称:mysql,代码行数:22,代码来源:client.py

示例6: connect_to_database

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def connect_to_database(host, database, user, password):
    try:
        connection = mysql.connector.connect(host=host, database=database, user=user, password=password)
        if connection.is_connected():
            print("Connected to MySQL database.")
            return connection
    except Error as e:
        print ("Error while connecting to MySQL", e) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:10,代码来源:getlogs_mysql.py

示例7: connect

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def connect(self):
        try:
            self._connection = mysql.connect(**self.settings)
        except mysql.Error as e:
            msg = 'Failure in connecting to database. Error: {0}'.format(e)
            raise DatabaseError(msg) 
开发者ID:RepoReapers,项目名称:reaper,代码行数:8,代码来源:database.py

示例8: disconnect

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def disconnect(self):
        try:
            if self._connection:
                self._connection.disconnect()
            self._connection = None
        except mysql.Error as e:
            msg = 'Failure in disconnecting from database. Error: {0}'.format(
                e
            )
            raise DatabaseError(msg) 
开发者ID:RepoReapers,项目名称:reaper,代码行数:12,代码来源:database.py

示例9: post

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def post(self, query, data=None):
        try:
            with self.cursor() as cursor:
                cursor.execute(query, params=data)

                if cursor.lastrowid is not None:
                    return cursor.lastrowid
                return cursor.rowcount
        except mysql.Error as e:
            msg = 'Failure in executing query {0}. Error: {1}'.format(query, e)
            raise DatabaseError(msg) 
开发者ID:RepoReapers,项目名称:reaper,代码行数:13,代码来源:database.py

示例10: _execute

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def _execute(self, conn=None, discard_results=False):
        """
        Execute and commit all composed statements and flushes the buffer
        """
        try:
            if not conn:
                conn = self.conn
        except (WaitTimeoutError, MySQLError):
            raise # unrecoverable

        try:
            cur = conn.cursor(dictionary=True, buffered=True)
            for stmt, params in self._query_buffer.items():
                log.debug('%s %s', stmt, params)
                cur.execute(stmt, params=params)
                if not discard_results:
                    return cur.fetchall()

                # we discard results from writes
                conn.commit()
                try:
                    cur.fetchall()
                except MySQLError:
                    # Will get "InternalError: No result set to fetch from."
                    # for SET statements. We can safely let this slide if the
                    # `execute` call passes
                    pass
        finally:
            # exceptions are an unrecoverable situation
            self._query_buffer.clear()
            cur.close() 
开发者ID:autopilotpattern,项目名称:mysql,代码行数:33,代码来源:client.py

示例11: setup_cosmic

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def setup_cosmic(self, isolation_mode=None):
        """Setup NSX in Cosmic"""
        nsx_query = None
        cosmic_controller_uuid = uuid.uuid4()
        cosmic_controller_guid = uuid.uuid4()

        cloud_cursor = self.cloud_db.cursor()
        try:
            nsx_query = ("INSERT INTO host (name,uuid,status,type,private_ip_address,private_netmask,"
                         "private_mac_address,storage_ip_address,storage_netmask,storage_mac_address,"
                         "storage_ip_address_2,storage_mac_address_2,storage_netmask_2,cluster_id,public_ip_address,"
                         "public_netmask,public_mac_address,proxy_port,data_center_id,pod_id,cpu_sockets,cpus,url,"
                         "fs_type,hypervisor_type,hypervisor_version,ram,resource,version,parent,total_size,"
                         "capabilities,guid,available,setup,dom0_memory,last_ping,mgmt_server_id,disconnected,"
                         "created,removed,update_count,resource_state,owner,lastUpdated,engine_state) VALUES "
                         "('Nicira Controller - %s','%s','Down','L2Networking','',NULL,NULL,'',NULL,NULL,"
                         "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0,"
                         "'com.cloud.network.resource.NiciraNvpResource','5.2.0.1-SNAPSHOT',NULL,NULL,NULL,"
                         "'%s',1,0,0,0,NULL,NULL,NOW(),NULL,0,'Enabled',NULL,NULL,'Disabled');" %
                         (self.master, cosmic_controller_uuid, cosmic_controller_guid))
            cloud_cursor.execute(nsx_query)
            self.cloud_db.commit()

            cloud_cursor.execute("SELECT LAST_INSERT_ID();")
            next_host_id = cloud_cursor.fetchone()[0]

            cloud_cursor.execute("SET FOREIGN_KEY_CHECKS=0;")

            nsx_query = ("INSERT INTO external_nicira_nvp_devices (uuid,physical_network_id,provider_name,device_name,"
                         "host_id) VALUES ('${nsx_cosmic_controller_uuid}',201,'NiciraNvp','NiciraNvp',%s);" %
                         next_host_id)
            cloud_cursor.execute(nsx_query)
            self.cloud_db.commit()

            nsx_query = ("INSERT INTO host_details (host_id, name, value) VALUES ({0},'transportzoneuuid','{1}'), ({0},"
                         "'physicalNetworkId','201'),({0},'adminuser','admin'),({0},'ip','{2}'),({0},'name',"
                         "'Nicira Controller - {2}'),({0},'transportzoneisotype','{3}'),({0},'guid','{4}'),({0},"
                         "'zoneId','1'),({0},'adminpass','admin'),({0},'niciranvpdeviceid','1');".format(
                          next_host_id, self.transport_zone_uuid, self.master, isolation_mode, cosmic_controller_guid))
            cloud_cursor.execute(nsx_query)
            self.cloud_db.commit()
        except Error as e:
            print("==> Error executing queries: ", e)
            print("==> Query: ", nsx_query)
        finally:
            if self.cloud_db.is_connected():
                cloud_cursor.close() 
开发者ID:MissionCriticalCloud,项目名称:bubble-toolkit,代码行数:49,代码来源:NSX.py

示例12: configure_kvm_host

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def configure_kvm_host(self):
        zones = parse('zones[*]').find(self.config)
        for zone in zones:
            hosts = parse('pods[*].clusters[*].hosts[*]').find(zone)
            for host in hosts:
                hostname = host.value['url'].split('/')[-1]
                host_ip = socket.gethostbyname(hostname)
                connection = {'hostname': hostname, 'username': host.value['username'],
                              'password': host.value['password']}
                cmds = [
                    ("cd /etc/openvswitch;"
                     "ovs-pki req ovsclient;"
                     "ovs-pki self-sign ovsclient;"
                     "ovs-vsctl -- --bootstrap set-ssl /etc/openvswitch/ovsclient-privkey.pem /etc/openvswitch/ovsclient-cert.pem /etc/openvswitch/vswitchd.cacert"),
                    "chown openvswitch:openvswitch /etc/openvswitch/*",
                    "systemctl restart openvswitch"
                ]

                print("==> Generate OVS certificates on %s" % hostname)
                for cmd in cmds:
                    self._ssh(cmd=cmd, **connection)

                print("==> Getting KVM host certificate from %s" % hostname)
                exitcode, stdout, stderr = self._ssh(
                    cmd='cat /etc/openvswitch/ovsclient-cert.pem | sed -z "s/\\n/\\\\n/g"', **connection)
                if exitcode == 0:
                    print("==> Create KVM host %s Transport Connector in Zone with UUID=%s" % (
                     hostname, self.transport_zone_uuid))
                    data = {"credential": {
                        "client_certificate": {
                            "pem_encoded": "".join(stdout)
                        },
                        "type": "SecurityCertificateCredential"
                    },
                        "display_name": hostname,
                        "integration_bridge_id": "br-int",
                        "transport_connectors": [
                            {
                                "ip_address": host_ip,
                                "transport_zone_uuid": self.transport_zone_uuid,
                                "type": "VXLANConnector"
                            },
                            {
                                "ip_address": host_ip,
                                "transport_zone_uuid": self.transport_zone_uuid,
                                "type": "STTConnector"
                            }
                        ]
                    }
                    _resp = self.session.post("https://%s/ws.v1/transport-node" % self.master, data=json.dumps(data))
                    if _resp.ok:
                        print("==> Setting NSX manager of %s to %s" % (hostname, self.master))
                        self._ssh(cmd="ovs-vsctl set-manager ssl:%s:6632" % self.master, **connection)
                    else:
                        print("==> Error setting up transport connector for %s, data='%s'" % (hostname, data)) 
开发者ID:MissionCriticalCloud,项目名称:bubble-toolkit,代码行数:57,代码来源:NSX.py

示例13: connect

# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import Error [as 别名]
def connect(self):
        """
        Creates connection to database, sets connection and cursor
        Connection to database can be loosed,
          if that happens you can use this function to reconnect to database
        """
        if self.engine == "mysql":
            found_connector = False
            try:
                # Import official mysql connector if exists
                import mysql.connector as mysql_module
                from mysql.connector import errorcode
                found_connector = True
            except ImportError:
                pass
            if not found_connector:
                # Check MySQLdb as secondary option
                try:
                    import MySQLdb as mysql_module
                except ImportError:
                    raise ValueError(
                        'Please, install mysql-connector or mysqlclient module before using this library.'
                    )
            # Connect to db
            try:
                self.connection = mysql_module.connect(**self.settings)
            except mysql_module.Error as err:
                if found_connector:
                    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                        raise ValueError("Wrong credentials, ACCESS DENIED")
                    elif err.errno == errorcode.ER_BAD_DB_ERROR:
                        raise ValueError(
                            "Database %s does not exists" % (self.settings['database'])
                        )
                    else:
                        raise ValueError(err)
                # @TODO Add detailed errors for MySQLdb
                raise err
        elif self.engine == "postgres":
            try:
                import psycopg2
            except ImportError:
                raise ValueError(
                    'Please, install psycopg2 module before using plugin.'
                )
            self.connection = psycopg2.connect(**self.settings)
        else:
            raise NotImplementedError(
                "Database engine %s not implemented!" % self.engine
            )

        self.cursor = self.connection.cursor() 
开发者ID:mastizada,项目名称:dbConnect,代码行数:54,代码来源:dbConnect.py


注:本文中的mysql.connector.Error方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。