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,))