python操作mysql数据库

本文介绍如何使用Python的pymysql模块进行MySQL数据库的基本操作,包括连接数据库、执行查询与插入语句等,并提供了一个通用的方法简化这些操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pymysql

python操作mysql的一个过程:

#1、连上数据库 账号、密码 ip 端口号 数据库
#2、建立游标
#3、执行sql
#4、获取结果
#5、关闭游标
#6、连接关闭

代码如下:

1、执行查询的操作
coon = pymysql.connect(host='XXX.XX.X.XX',user='jxz',passwd='123456',
port=3306,db='jxz',charset='utf8')

#port必须写int类型,
#charset这里必须写utf8

cur = coon.cursor() #建立游标
cur.execute('select * from stu;')#执行sql语句
res = cur.fetchall() #获取所有返回的结果
print(res)
cur.close() #关闭游标
coon.close() #关闭连接


代码如下:
1、执行插入的操作

coon = pymysql.connect(
host='xxx.xx.xx.xxx',user='jxz',passwd='123456',
port=3306,db='jxz',charset='utf8'
#port必须写int类型,
#charset这里必须写utf8
)
cur = coon.cursor() #建立游标
cur.execute('insert into stu (id,name,sex) VALUE (1,"username","女");')
# 在mysql中使用删除 delete 更新 update 插入 insert,必须执行coomit,否则不生效。
coon.commit() #必须得coomit
res = cur.fetchall() #获取所有返回的结果
print(res)
cur.close() #关闭游标
coon.close() #关闭连接

为了以后方便使用定义了一个操作数据库的方法:


def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
import pymysql
coon = pymysql.connect(user=user,
host=host,
port=port,
passwd=passwd,
db=db,
charset=charset
)
cur = coon.cursor() #建立游标
cur.execute(sql)#执行sql
if sql.strip()[:6].upper()=='SELECT':
res = cur.fetchall()
else:
coon.commit()
res = 'ok'
cur.close()
coon.close()
return res

调用该方法:
res= my_db(host='118.24.3.40',user='jxz',passwd='123456',

db='jxz',port=3306,charset='utf8',sql="select * from stu; ")
print(res)
 

转载于:https://www.cnblogs.com/bo-test1985-dd/p/8929083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值