赞
踩
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = 'tedu',
db = 'tedu',
charset = 'utf8'
)
cursor = conn.cursor()
insert_dep = 'insert into departments values(%s, %s)' ##实现增操作
jihe = [(2, '运维部'), (3, '测试部'), (4, '行政部'), (5, '战略部')] ##把值放进去元组,进行批量插入
cursor.executemany(insert_dep, jihe) ##执行语句
conn.commit() ##提交直接结果
cursor.close()
conn.close()
cursor = conn.cursor()
update_dep = 'update departments set dep_name=%s where dep_id=%s' ##实现改操作
cursor.execute(update_dep, ('人力资源部', 1)) ##单个值修改,元组内的值对应sql语句的占位符
conn.commit()
cursor.close()
conn.close()
cursor = conn.cursor()
del_dep = 'delete from departments where dep_id=%s' ##实现删操作
cursor.execute(del_dep, (5, )) ##单个删除,元组内仅一个值,所以添加个,
conn.commit()
cursor.close()
conn.close()
cursor = conn.cursor()
query_dep = 'select * from departments' ##实现查询操作
cursor.execute(query_dep)
r = cursor.fetchall() ##全部值取出,这里可以用cursor.fetchone()或
print(r) fetchmany()
cursor.close()
conn.close()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。