Python MySQL 数据库连接
要连接 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 的数据库。
-
我们创建了一个包含 FIRST_NAME、LAST_NAME、AGE、SEX 和 INCOME 列的 EMPLOYEE 表。
-
我们用来连接 MySQL 的凭据是用户名: root , 密码: password .
你可以使用 连接() 构造函数。这接受用户名、密码、主机和你需要连接的数据库的名称(可选),并返回 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',)
你还可以通过将凭据(用户名、密码、主机名和数据库名称)传递给 MySQL 来建立与 MySQL 的连接 连接.MySQLConnection() 如下所示:
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()