1、安装mysql-connector-python
要在 Python 中连接 MySQL 数据库 “test”,可以使用 “mysql-connector-python” 包。首先,确保已经安装了该包。可以使用 pip 命令进行安装:
pip install mysql-connector-python
或
pip install mysql-connector-python -i https://pypi.tuna.tsinghua.edu.cn/simple
2、连接 MySQL 数据库
一定要开启数据库,然后,在 Python 代码中,可以使用以下代码来连接数据库test:
import mysql.connector
# 创建连接
cnx = mysql.connector.connect(user='username', password='password',
host='localhost', database='test')
# 创建游标对象
cursor = cnx.cursor()
# 执行 SQL 查询
query = "SELECT * FROM students"
cursor.execute(query)
# 获取结果集并打印
for row in cursor:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
在上面的代码中,将数据库连接的参数替换为您的实际值,例如用户名和密码。然后创建一个连接对象并创建一个游标对象,使用游标执行 SQL 查询并遍历结果集。最后,关闭游标和连接对象。
上述代码运行结果与创建数据库的时候相同:
D:\Anaconda3\envs\py37\python.exe D:\my_project\mynlp\tf2-bert-textclassification\pymysql.py
(1, 'John Doe', 20, 'Male', 'john.doe@example.com', datetime.datetime(2023, 4, 10, 20, 30, 13))
(2, 'Alice Smith', 22, 'Female', 'alice.smith@example.com', datetime.datetime(2023, 4, 10, 20, 32, 13))
(3, 'Bob Johnson', 21, 'Male', 'bob.johnson@example.com', datetime.datetime(2023, 4, 10, 20, 32, 13))
(4, 'Jane Doe', 19, 'Female', 'jane.doe@example.com', datetime.datetime(2023, 4, 10, 20, 32, 13))
如果你出现下面的报错:
Traceback (most recent call last):
File "D:\my_project\mynlp\tf2-bert-textclassification\pymysql.py", line 1, in <module>
import mysql.connector
File "D:\Anaconda3\envs\py36\lib\site-packages\mysql\connector\__init__.py", line 32, in <module>
from .connection_cext import CMySQLConnection
File "D:\Anaconda3\envs\py36\lib\site-packages\mysql\connector\connection_cext.py", line 40, in <module>
from .abstracts import MySQLConnectionAbstract
File "D:\Anaconda3\envs\py36\lib\site-packages\mysql\connector\abstracts.py", line 33
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
这个错误可能是因为你使用的 Python 版本不支持 annotations 特性,该特性是在 Python 3.7 版本中引入的。建议将 Python 版本升级到 3.7 及以上版本,或者去掉代码中的 from future import annotations 这一行,如果不需要使用该特性的话。
3、修改数据库
先解释什么是主键?
在关系型数据库中,主键是一列或者一组列,它们的值能够唯一地标识表中每一行数据。在 MySQL 中,主键可以由一个或多个列组成,并且主键列必须满足唯一性和非空性的条件。在这里,错误提示中提到的 students.PRIMARY 就是 students 表的主键,它由 id 这一列组成。出现重复主键的错误提示意味着表中已经存在了一行 id 列值为 1 的数据,而我们尝试向表中插入的新数据中 id 列的值也为 1,这就违反了主键的唯一性限制。
import mysql.connector
# 建立 MySQL 数据库连接
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='localhost',
database='test')
cursor = cnx.cursor()
# 定义 INSERT 语句
add_student = ("INSERT INTO students "
"(id, name, age) "
"VALUES (%s, %s, %s)")
# 插入一条新记录
new_student = (1, 'Alice', 20)
cursor.execute(add_student, new_student)
# 提交修改
cnx.commit()
# 关闭连接
cursor.close()
cnx.close()
在这个示例中,我们首先建立了一个 MySQL 数据库连接,然后定义了一个 INSERT 语句,将一条新记录插入到 students 表中,最后提交修改并关闭连接。注意,如果表中已经存在相同 id 的记录,那么这个操作会抛出一个 mysql.connector.errors.IntegrityError 异常。你可以通过 try-except 语句来捕获并处理这个异常,或者使用 INSERT IGNORE 语句来插入记录,如果记录已经存在,则忽略插入操作。
当我运行上述代码之后出现下面的报错:
Traceback (most recent call last):
File "D:\Anaconda3\envs\py37\lib\site-packages\mysql\connector\connection_cext.py", line 613, in cmd_query
query_attrs=self._query_attrs,
_mysql_connector.MySQLInterfaceError: Duplicate entry '1' for key 'students.PRIMARY'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\my_project\mynlp\tf2-bert-textclassification\addmysql.py", line 15, in <module>
cursor.execute(add_student, new_student)
File "D:\Anaconda3\envs\py37\lib\site-packages\mysql\connector\cursor_cext.py", line 334, in execute
raw_as_string=self._raw_as_string,
File "D:\Anaconda3\envs\py37\lib\site-packages\mysql\connector\connection_cext.py", line 618, in cmd_query
) from err
mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '1' for key 'students.PRIMARY'
这个错误是因为在添加数据时出现了重复的主键值1。主键1是一种唯一标识符,用于确保表中每一行都具有唯一的标识符。您需要确保在添加新数据时,主键值是唯一的,否则会出现上述的错误。如果主键值已经存在于表中,您需要更新该行而不是插入新行。可以使用INSERT INTO…ON DUPLICATE KEY UPDATE语句在发生重复键时执行更新。
为了解决这个问题,我将主键修改为6
import mysql.connector
# 建立 MySQL 数据库连接
cnx = mysql.connector.connect(user='root', password='password',
host='localhost', database='test')
cursor = cnx.cursor()
# 定义 INSERT 语句
add_student = ("INSERT INTO students "
"(id, name, age) "
"VALUES (%s, %s, %s)")
# 插入一条新记录
new_student = (6, 'Alice 2023 helloworld', 20)
cursor.execute(add_student, new_student)
# 提交修改
cnx.commit()
# 关闭连接
cursor.close()
cnx.close()
运行之前的代码:可以发现已经添加