python实现操作数据库完成基本的增删改查

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,))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值