一、MySQL Connector Python 模块介绍
MySQL Connector Python 是 Python 程序语言的一个标准数据库接口,可用于将 Python 连接到 MySQL 数据库。该模块是由 MySQL AB 公司开发和维护,遵循 MySQL 官方规范。MySQL Connector Python 可在 Python 中使用,允许 Python 开发人员编写 Python 应用程序,该应用程序与 MySQL 服务器进行通信。
MySQL Connector Python 可在 Python 2.7 和 3.4 及更高版本中使用,官方提供了 Windows、Linux 和 MacOS 的二进制文件下载,方便在不同环境中使用。
安装 MySQL Connector Python 模块,可通过 pip 工具进行安装
pip install mysql-connector-python
二、MySQL Connector Python 模块常见操作
1、连接 MySQL 数据库
在 Python 中连接 MySQL 数据库需要使用到 MySQL Connector Python 模块提供的 connect() 方法。connect() 方法的返回值是一个 MySQLConnection 类型的对象
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password"
)
print(mydb)
输出结果:<mysql.connector.connection_cext.CMySQLConnection object at 0x7f57c8e8ce10>
2、执行 SQL 语句
连接到 MySQL 数据库后,可以使用 execute() 方法来执行 SQL 语句,例如查询、插入、更新或删除数据
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
输出结果:(1, 'John', 'Doe', 'john@example.com')
3、插入数据
使用 execute() 方法和 SQL INSERT INTO 语句将数据插入数据库
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
4、更新数据
使用 execute() 方法和 SQL UPDATE 语句更新数据库中的数据
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
5、删除数据
使用 execute() 方法和 SQL DELETE FROM 语句删除数据库中的数据
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
三、MySQL Connector Python 模块优点
1、易于学习和使用
Python 语言的简洁性和 MySQL Connector Python 模块的易于使用,使得使用 Python 连接 MySQL 数据库比使用其他编程语言更为简单。
2、高度兼容性
MySQL Connector Python 模块可以很好地与多个操作系统和数据库版本进行兼容。此外,该模块遵循 MySQL 官方规范,保证了在连接到 MySQL 服务器时的灵活性。
3、效率高
MySQL Connector Python 模块底层采用 C 所写,通过调用底层 C 函数来在 Python 中实现连接和事务交互操作,提高了模块的执行效率。
4、伸缩性好
MySQL Connector Python 模块提供了支持分布式数据库访问的 API 接口,可在更大的集群中使用。
5、开发文档完善
MySQL Connector Python 模块提供了详细的开发文档和示例代码,方便开发人员学习和使用该模块。
原创文章,作者:TVTQM,如若转载,请注明出处:https://www.506064.com/n/349368.html