📜  Python MySQL-数据库连接

📅  最后修改于: 2020-11-07 07:39:10             🧑  作者: Mango


要与MySQL连接,(一种方法是)在系统中打开MySQL命令提示符,如下所示-

数据库连接

它在这里要求输入密码;您需要输入安装时设置为默认用户(root)的密码。

然后与MySQL建立连接,显示以下消息-

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

您可以随时在mysql>提示符下使用exit命令从MySQL数据库断开连接。

mysql> exit
Bye

使用Python与MySQL建立连接

在使用Python建立与MySQL数据库的连接之前,假定-

  • 我们创建了一个名为mydb的数据库。

  • 我们创建了一个表EMPLOYEE,该表的列为FIRST_NAME,LAST_NAME,AGE,SEX和INCOME。

  • 我们用于连接MySQL的凭据是用户名-root ,密码-password

您可以使用connect()构造函数建立连接。它接受用户名,密码,主机和您需要连接的数据库名称(可选),并返回MySQLConnection类的对象。

以下是连接MySQL数据库“ mydb”的示例。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("SELECT DATABASE()")

#Fetch a single row using fetchone() method.
data = cursor.fetchone()

print("Connection established to: ",data)

#Closing the connection
conn.close()

输出

在执行时,此脚本产生以下输出-

D:\Python_MySQL>python EstablishCon.py
Connection established to: ('mydb',)

您还可以通过将凭据(用户名,密码,主机名和数据库名)传递给connection.MySQLConnection()来建立与MySQL的连接,如下所示-

from mysql.connector import (connection)

#establishing the connection
conn = connection.MySQLConnection(
   user='root', password='password', host='127.0.0.1', database='mydb'
)

#Closing the connection
conn.close()