要往MySQL数据库中存取数据,可以使用Python的MySQL Connector模块。
以下是示例代码:
连接数据库
import mysql.connector # 连接数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", ) # 获取游标 mycursor = mydb.cursor()
创建数据库
# 创建数据库 mycursor.execute("CREATE DATABASE mydatabase")
创建表格
# 连接数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # 获取游标 mycursor = mydb.cursor() # 创建表格 mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
插入数据sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("John", "Highway 21") mycursor.execute(sql, val) # 提交更改 mydb.commit() # 输出插入的行号 print(mycursor.rowcount, "record inserted.")
查询数据
# 查询数据 mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult: print(x)
更新数据
# 更新数据 sql = "UPDATE customers SET address = %s WHERE name = %s" val = ("Valley 345", "John") mycursor.execute(sql, val) # 提交更改 mydb.commit() # 输出更新的行数 print(mycursor.rowcount, "record(s) affected")
删除数据
# 删除数据 sql = "DELETE FROM customers WHERE address = 'Mountain 21'" mycursor.execute(sql) # 提交更改 mydb.commit() # 输出删除的行数 print(mycursor.rowcount, "record(s) deleted")
注意:在使用模块前需要先安装:pip install mysql-connector-python
raise ReadTimeoutError(self._pool, None, "Read timed out.") pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='pypi.tuna.tsinghua.edu.cn', port=443): Read timed out.
这个错误是pip连接pypi.tuna.tsinghua.edu.cn超时导致的。可能是因为网络连接不稳定或该主机无法访问。
以下是一些可能的解决方法:
-
检查网络连接是否正常。
-
检查pypi.tuna.tsinghua.edu.cn是否正常运行。
-
尝试使用其他镜像源。例如,尝试使用国内的镜像源,如阿里云或华为云。
-
尝试使用代理。例如,使用socks5代理:
pip install -U requests[socks] pip install --proxy socks5h://127.0.0.1:1080 package_name
其中,127.0.0.1:1080
是你的代理服务器地址和端口。
希望这些解决方法能帮到你。
Installing collected packages: requests Attempting uninstall: requests Found existing installation: requests 2.28.1 Uninstalling requests-2.28.1: Successfully uninstalled requests-2.28.1 Successfully installed requests-2.28.2
这与安装requests
包相关的信息,显示旧版本的requests包(2.28.1)已经被成功卸载并安装了新版本的包(2.28.2)。
如果你想验证安装是否成功,可以使用以下Python代码检查:
import requests print(requests.__version__)
代码将输出requests包的版本号。如果安装成功,将输出2.28.2。
Requirement already satisfied: protobuf<=3.20.3,>=3.11.0 in c:\users\administrator\appdata\local\programs\python\python310\lib\site-packages (from mysql-connector-python) (3.20.3) Installing collected packages: mysql-connector-python Successfully installed mysql-connector-python-8.0.32
这个信息表明mysql-connector-python
包已经安装成功。如果你想验证安装是否成功,可以使用以下Python代码检查:
import mysql.connector print(mysql.connector.__version__)