使用python和mysql官方提供驱动对数据库进行操作。
环境
windows7 64位
python 3.4.3
mysql5.0
下载安装驱动
请根据自己的操作系统和python版本下载相应驱动。
我在win7下安装驱动的时候提示我找不到python环境,要求python必须是通过msi直接安装才可以。
没办法,卸载重新安装了才可以。
连接数据库
介绍这里mysql.connector支持的数据库连接方式。
使用connect()构造器创建连接:
Python
import mysql.connector
# Connect with the MySQL Server
cnx = mysql.connector.connect(user='root',
password='zhyea.com',
host='127.0.0.1',
database='test')
cnx.close()
import mysql.connector
# Connect with the MySQL Server
cnx = mysql.connector.connect(user='root',
password='zhyea.com',
host='127.0.0.1',
database='test')
cnx.close()
也可以使用connection.MySQLConnection()类:
Python
from mysql.connector import (connection)
# Connect with the MySQL Server
cnx = connection.MySQLConnection(user='root',
password='zhyea.com',
host='127.0.0.1',
database='test')
cnx.close()
from mysql.connectorimport (connection)
# Connect with the MySQL Server
cnx = connection.MySQLConnection(user='root',
password='zhyea.com',
host='127.0.0.1',
database='test')
cnx.close()
上面提到的两种方案都是可行的,而且性能一样。但是connect()用得更多一些,我个人也比较喜欢这种方式。
要处理连接异常的话,可以使用try/catch声明来捕捉异常:
Python
import mysql.connector
from mysql.connector import errorcode
# Connect with the MySQL Server
try:
cnx = mysql.connector.connect(user='root',
password='zhyea.com',
host='127.0.0.1',
database='test11')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name and password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database dosen't exist")
else:
print(err)
else:
cnx.close()
import mysql.connector
from mysql.connectorimport errorcode
# Connect with the MySQL Server
try:
cnx = mysql.connector.connect(user='root',
password='zhyea.com',
host='127.0.0.1',
database='test11')
except mysql.connector.Erroras err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name and password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database dosen't exist")
else:
print(err)