- mysql 操作
import pymysql
#创建数据库连接
conn=pymysql.connect (host=“127.0.0.1”,port=3306,
user=“root”,password=“root”,
database=“stu”,charset=“utf8”)
if conn==None :
print(“数据库连接失败”)
else:
print(“数据库连接成功”)
#查询数据cursor
#拿到游标对象,来查询数据
cursor=conn.cursor()
sql=‘select *from student’
cursor.execute(sql)
#查询数据的具体信息(元组)
content=cursor.fetchall()
print(content)
- 构建一个utils模块,以供调用
:
import pymysql
创建数据库连接
def get_conn():
conn = pymysql.connect(host=“127.0.0.1”, port=3306,
user=“root”, password=“root”,
database=“cov”, charset=“utf8”)
if conn == None:
print(“数据库连接失败”)
else:
print(“数据库连接成功”)
cursor = conn.cursor()
return conn, cursor
释放资源
def close(conn, cursor):
cursor.close()
conn.close()
3. 数据增删改查:
from day05 import utilss
#查询
def query():
# 获取数据库连接
conn,cursor=utilss.get_conn()
sql=‘select *from student’
cursor.execute(sql)
content=cursor.fetchall()
print(content)
#释放资源
utilss.close(conn,cursor )
“”"
#插入数据
def insert():
# 获取数据库连接
conn,cursor=utilss.get_conn()
sql=‘insert into student values(null,“dapao”,17,“python”,90);’
cursor.execute(sql)
#提交事务
conn.commit()
utilss.close(conn, cursor)
#更新数据 修改
def update():
conn, cursor = utilss.get_conn()
sql=‘update sudent set name=“jiji” where id=3’
cursor.execute(sql)
cursor.commit()
utilss.close(conn, cursor)
“”"
#删除
def delete():
conn, cursor = utilss.get_conn()
sql=‘delete from student where id=6’
cursor.execute