如何用Python连接MySQL数据库详细示例教程

一、环境说明

MySQL版本:MySQL 8.0.40-arm64

Python版本:Python 3.13

PyMySQL版本:PyMySQL 1.1.1

请在电脑中安装以上软件并配置好开发环境。

二、Python使用MySQL的示例代码:

# 1. 导入模块
import pymysql

# 2. 连接数据库
connect = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    passwd = 'your passwd',
    db = 'your database name',
    charset = 'utf8'
)

# 3. 执行SQL语句
cursor = connect.cursor()  # 获取游标
sql = "show databases;"  # 获取所有数据库
cursor.execute(sql)  # 执行语句
print(cursor.fetchall())

# 4. 关闭数据库
cursor.close()
connect.close()


三、PyMySQL常见类和方法

01:pymysql.connect() 属性【参数】

# 2、连接数据库
connect = pymysql.Connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    passwd = 'your passwd',
    db = 'your database name',
    charset = 'utf8'
)


# host        MySQL服务器地址,IP地址或域名
# port        MySQL服务器端口号
# user        用户名
# passwd      密码
# db          数据库名称
# charset     数据库连接编码


02:connect 对象支持的方法

# 创建游标并返回游标对象
cursor = connect.cursor()  

# 提交当前事务
connect.commit()

# 回滚当前事务
connect.rollback()

# 关闭连接
connect.close()



03:cursor 对象支持的方法(执行sql语句并获得结果)

# 获取所有数据库
sql = "show databases;"  
dbs = cursor.execute(sql)  # 执行sql语句
print(cursor.fetchall())


# execute(op)        执行一个SQL命令
# fetchall()         获取结果集中的所有数据
# close()            关闭游标对象

# fetchone()         取得结果集的一行数据
# fetchmany(size)    获取结果集的size行数据
# rowcount           返回数据条数或影响行数




四、练习代码

01:获取数据

# 1、导入模块
import pymysql

# 2、连接数据库
connect = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    passwd = 'your passwd',
    db = 'your database name',
    charset ='utf8'
)

# 3、执行SQL语句
cursor = connect.cursor()

sql = "select * from teachers;"  # 获取teachers表的数据
dbs = cursor.execute(sql)
# print(dbs)
# print(cursor.fetchone())
print(cursor.fetchall())

# 4、关闭数据库
cursor.close()
connect.close()


02:插入数据

# 1、导入模块
import pymysql

# 2、连接数据库
connect = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    passwd = 'your passwd',
    db = 'your database name',
    charset = 'utf8'
)

# 3、执行SQL语句
cursor = connect.cursor()
sql = "insert into teachers values(4,'周老师');"  # 向teachers表中插入values的值
dbs = cursor.execute(sql)
# 当对表或表内数据进行插入,修改,删除时,要使用commit提交当前事务
connect.commit()

# 4、关闭数据库
cursor.close()
connect.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值