Python-MySQL-入门

时间:2020-02-23 14:43:03  来源:igfitidea点击:

在本教程中,我们将学习使用Python连接到MySQL数据库。

安装适用于Python的MySQL Connector

要使用MySQL数据库,我们必须首先安装mysql-connector软件包。

我们将使用PIP软件包管理器安装" mysql-connector"。

在终端中运行以下命令以安装软件包。

$pip install mysql-connector

您还可以签出" mysql-connector-python"包以使用Python连接到MySQL数据库。

导入mysql.connector

安装mysql-connector软件包后,继续通过编写以下代码将其导入。

import mysql.connector

连接数据库

编写以下Python代码以连接到MySQL数据库。

cnx = mysql.connector.connect(
  user='USERNAME',
  password='PASSWORD',
  host='127.0.0.1',
  database='DATABASE'
)

其中," USERNAME"是您数据库的用户名。
PASSWORD是用户名的密码。
DATABASE是您要连接的数据库的名称。
主机设置为" 127.0.0.1",表示本地主机。

在下面的示例中,我连接到系统上的mydb数据库。
我的系统的用户名是" root",密码是" root1234"。

cnx = mysql.connector.connect(
  user='root',
  password='root1234',
  host='127.0.0.1',
  database='mydb'
)

处理数据库错误

在尝试建立数据库连接时,我们可能会遇到错误。
因此,要处理错误,我们可以借助try-except块。

在下面的Python程序中,我们将连接到数据库并使用try-except块来处理任何错误。

# import module
import mysql.connector

# import errorcode
from mysql.connector import errorcode

try:
  cnx = mysql.connector.connect(
      user='root',
      password='root1234',
      host='127.0.0.1',
      database='mydb'
  )
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('Invalid credential. Unable to access database.')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('Database does not exists')
    else:
        print('Failed to connect to database')

print('Successfully connected to the database.')

# close connection
cnx.close()

成功后,上面的代码将打印以下输出。

Successfully connected to the database.

关闭数据库连接

在完成数据库任务之后,关闭数据库连接是一个好习惯。

要关闭连接,我们使用close()方法。

在下面的Python程序中,我们将关闭我们之前建立的数据库连接。

cnx.close()