Python For MySQL 使用连接器连接 ( 一)
来源:互联网 发布:js中array的indexof 编辑:程序博客网 时间:2024/06/05 08:04
connect()构造函数创建一个并返回一个连接到MySQL服务器 MySQLConnection对象。
下面的例子显示了如何连接到MySQL服务器:
import mysql.connectorcnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees')cnx.close()
还可以创建连接对象使用connection.MySQLConnection()类:
from mysql.connector import (connection)cnx = connection.MySQLConnection(user='scott', password='tiger', host='127.0.0.1', database='employees')cnx.close()
这两种方法,使用 connect()直接构造函数或类,是有效的和功能相同,但使用 connector()优先使用在本手册在大多数例子。
处理连接错误,使用 try声明和捕捉所有的错误使用errors.Error例外:
import mysql.connectorfrom mysql.connector import errorcodetry: cnx = mysql.connector.connect(user='scott', database='testt')except mysql.connector.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: cnx.close()
如果你有大量的连接参数,最好让他们在字典和使用 **接线员:
import mysql.connectorconfig = { 'user': 'scott', 'password': 'tiger', 'host': '127.0.0.1', 'database': 'employees', 'raise_on_warnings': True,}cnx = mysql.connector.connect(**config)cnx.close()
使用连接器/ Python C扩展
连接器/ Python 2.1.1, use_pure连接参数决定是否使用纯Python接口连接到MySQL,C或C扩展使用MySQL客户端库(见第八章,连接器/ Python C扩展)。默认值是True(使用纯Python实现)。设置 use_pure来 False导致连接使用C扩展如果连接器/ Python安装包括它。下面的例子是类似于其他先前的includion但显示use_pure=False.
连接的命名参数 connect()电话:
import mysql.connectorcnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees', use_pure=False)cnx.close()
连接使用一个论点词典:
import mysql.connectorconfig = { 'user': 'scott', 'password': 'tiger', 'host': '127.0.0.1', 'database': 'employees', 'raise_on_warnings': True, 'use_pure': False,}cnx = mysql.connector.connect(**config)cnx.close()
还可以直接使用C扩展,通过导入 _mysql_connector模块而不是 mysql.connector模块。
0 0
- Python For MySQL 使用连接器连接 ( 一)
- 连接器/ Python连接池
- mysql与python连接器 MySQL Connector/Python
- 使用python连接mysql
- 使用Python连接MySQL
- 使用连接器/ Python 5.4查询数据
- mysql 连接器
- Python连接MySQL数据库,for Mac
- 使用Python连接MySQL数据库
- 使用Python连接MySQL数据库
- python连接MYSql数据库python连接MYSql数据库 使用 MySQLdb
- 第1章 MySQL Python连接器的介绍
- 使用路由组连接器连接Exchange 2003路由组
- 解决3389服务器只能使用强行连接器连接问题解决方法
- Python下使用MySQLdb连接MySQL出错的解决办法(一)
- Python 专题一 python 使用 MySQL
- python中使用MySQLdb连接mysql
- python中使用MySQLdb连接mysql
- Android获取View的宽高与View.measure详解
- 算法之绪论
- Hibernate中BookClassId作为外键,Book.jsp访问BookClassName
- artDialogV6 关闭弹窗
- Sicily.找零总数
- Python For MySQL 使用连接器连接 ( 一)
- 数据库操作的异常Cannot perform this operation because the connection pool has been close
- Perl 6 网页抓取
- hibernate4之后HibernateUtil类的编写
- php命令行查看已安装的模块的方式
- junction
- Gradle:构建项目
- leetcode 110: Balanced Binary Tree
- hadoop2/MRv2 YARN整体了解 ResourceManager