前言
MySQL连接器(Python),用于让Python程序能够访问MySQL数据库。要想让Python应用程序正确高效地使用MySQL数据,就需要深入了解MySQL连接器的特性和使用方法。
上篇文章👉《 【MySQL连接器(Python)指南】03-MySQL连接器(Python)安装》 介绍了连接器的安装方法和步骤,这篇介绍如何使用连接器。
使用连接器连接 MySQL
connect()
构造函数创建了一个到MySQL服务器的连接,并返回一个MySQL连接对象。下面的示例显示了如何连接到MySQL服务器:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
也可以使用 connection.MySQLConnection()
创建连接对象。MySQL连接()类:
from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
这两种方法等效,但是使用 connect()
的方法是首选。
若要处理连接错误,请使用try语句,并使用errors.Error
捕获所有错误:
import mysql.connector
from mysql.connector import errorcode
try:
cnx