liace

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

py 连接mysql

 

 

要在Python中连接MySQL,首先需要安装pymysql库。可以使用以下命令安装该库:

Copy
pip install pymysql

在安装完pymysql库后,可以使用以下示例代码连接到MySQL数据库:

Copy
import pymysql

# 连接数据库
connection = pymysql.connect(host='localhost',
                             user='your_username',
                             password='your_password',
                             database='your_database',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    # 执行SQL语句
    with connection.cursor() as cursor:
        sql = "SELECT * FROM your_table"
        cursor.execute(sql)
        results = cursor.fetchall()
        for row in results:
            # 处理查询结果
            print(row)
finally:
    # 关闭数据库连接
    connection.close()

在上述代码中,需要替换your_usernameyour_passwordyour_databaseyour_table为实际的数据库用户名、密码、数据库名称和表名。如果数据库位于本地主机上,则将host参数设置为localhost,否则将其替换为数据库的主机名或IP地址。

请注意,这只是连接MySQL数据库的基本示例,还可以根据需要执行其他SQL语句或执行其他操作。

posted on   凉策  阅读(28)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示