python实现操作数据库完成基本的增删改查
python实现操作数据库完成基本的增删改查1.连接数据库数据库使用MySQL,连接数据库驱动采用mysql-connector安装mysql-connector的方式python -m pip install mysql-connector然后只需要在项目中导入即可import mysql.connector连接数据库cnn = mysql.connector.connect(host="loc
·
python实现操作数据库完成基本的增删改查
1.连接数据库
数据库使用MySQL,连接数据库驱动采用mysql-connector
安装mysql-connector的方式
python -m pip install mysql-connector
然后只需要在项目中导入即可
import mysql.connector
连接数据库
cnn = mysql.connector.connect(
host="localhost",
port=3306,
user='root',
passwd='****.',
database='test')
2. 操作
1. 实现插入
# 使用cursor()方法获取操作指针
cursor = cnn.cursor()
# 使用execute方法执行SQL语句
cursor.execute("insert into table1 (name,id,people1,people2,people3,result) values (%s,%s,%s,%s,%s,%s)",(self.name,self.id,self.p1,self.p2,self.p3,res))
cursor.execute("select * from table1 where name= %s",(self.name,))
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
2.实现查询
cursor.execute("select * from table1")
#fetchall()用于获取所有数据
data = cursor.fetchall()
3. 实现修改
cursor = cnn.cursor()
cursor.execute("update table1 set name= %s where id = %s",(self.name,self.id))
4.实现删除
cursor = cnn.cursor()
cursor.execute("delete from table1 where id= %s",(self.id,))

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)