# 安装 pymysql 库
# 你可以使用 pip 来安装 pymysql,命令如下:
# pip install pymysql
import pymysql
# 连接到 MySQL 数据库的示例代码
def connect_to_database():
# 创建连接对象
connection = pymysql.connect(
host='localhost', # 数据库主机地址
user='your_username', # 数据库用户名
password='your_password', # 数据库密码
database='your_database' # 数据库名称
)
try:
# 创建游标对象
with connection.cursor() as cursor:
# 执行 SQL 查询
sql = "SELECT * FROM your_table"
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
finally:
# 关闭数据库连接
connection.close()
# 调用函数
connect_to_database()
pip install pymysql 命令来安装 pymysql 库。pymysql.connect() 方法创建一个数据库连接对象。需要提供主机地址、用户名、密码和数据库名称等参数。connection.cursor() 方法创建游标对象,用于执行 SQL 查询。cursor.execute() 方法执行 SQL 查询,并通过 cursor.fetchall() 获取查询结果。希望这段代码和解释对你有帮助!
上一篇:mysql不允许远程连接
下一篇:mysql查询事务隔离级别
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站