# 文件名:db
import pymysql
#创建连接
def get_conn():
return pymysql.connect(
host='localhost',
user='root',
password='1980897959',
database='flask',
charset='utf8'
)
# 查询
def query_data(sql):
conn = get_conn()
try:
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute(sql)
return cursor.fetchall()
finally:
conn.close()
# 插入和更新
def insert_or_update(sql):
conn = get_conn()
try:
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
finally:
conn.close()
# 测试
import db
query_sql = "select * from user"
insert_sql = '''insert user values("ylf","123")'''
db.insert_or_update(insert_sql)
print(db.query_data(query_sql))
# 结果:
[{'username': 'dyl', 'password': '123'}, {'username': 'ylf', 'password': '123'}]
网友评论