Python全栈 MySQL 数据库 (引擎、事物、pymysql模块、orm)
开局一张图
# frist.py
import pymysql
# 创建数据库对象
db = pymysql.connect(host="localhost", user="root",
password="123456", database="db4",
charset="utf8")
# 利用db方法创建游标对象
cur = db.cursor()
# 利用游标对象的execute()方法执行SQL命令
cur.execute("insert into sheng values\
(16,300000,'台湾省');")
# 提交到数据库
db.commit()
# 关闭游标对象
cur.close()
# 断开数据库链接
db.close()
# 增 删 改
import pymysql
# 创建数据库链接
# 链接到db4库
db = pymysql.connect(host="localhost", user="root",
password="123456", database="db4",
charset="utf8")
# 创建游标
cur = db.cursor()
try:
# 添加记录
cur.execute("insert into sheng values (17,168800,'浙江');")
# 修改记录
cur.execute("update sheng set id=666 where id=17;")
# 删除记录
cur.execute("delete from sheng where s_name='浙江';")
# 截获EXception类型错误
except Exception as e:
# 出现异常后回滚
db.rollback()
# 输出错误
print("Error ", e)
else:
# 提交数据
db.commit()
# 关闭游标
cur.close()
# 断开数据库链接
db.close()
# 查询
import pymysql
# 创建数据库链接
db = pymysql.connect(host="localhost", user="root",
password="123456", database="db4",
charset="utf8")
# 创建游标
cur = db.cursor()
try:
# 查找
cur.execute("select * from sheng;")
# 取出一条记录就少一条
print("***************************")
data1 = cur.fetchone()
print(data1)
print("***************************")
data2 = cur.fetchmany(3)
for i in data2:
print(i)
print("***************************")
# 遍历取出数据
data3 = cur.fetchall()
for x in data3:
print(x)
# 提交数据
db.commit()
except Exception as e:
db.rollback()
print("Error ", e)
# 关闭游标
cur.close()
# 断开数据库链接
db.close()
# 参数化
import pymysql
# 创建数据库链接
db = pymysql.connect(host="localhost", user="root",
password="123456", database="db4",
charset="utf8")
# 创建游标
cur = db.cursor()
try:
s_id = input("请输入省的编号")
s_name = input("请输入省的名字")
# 用占位符参数化数据
sql_insert = "insert into sheng(s_id,s_name) values(%s,%s)"
# execute方法 传参必须是列表
cur.execute(sql_insert, [s_id, s_name])
# 提交数据
db.commit()
except Exception as e:
db.rollback()
print("Error ", e)
# 关闭游标
cur.close()
# 断开数据库链接
db.close()
# mysqlpython.py
# 导入mysql模块
from pymysql import *
class MysqlPython:
def __init__(self, database, # 库
host="127.0.0.1", # ip地址
user="root", # 用户名
password="123456", # 密码
port=3306, # 端口
charset="utf8"): # 字符集
self.host = host
self.database = database
self.user = user
self.password = password
self.port = port
self.charset = charset
def open(self): # 创建数据库链接函数
self.db = connect(host=self.host,
database=self.database,
user=self.user,
password=self.password,
port=self.port,
charset=self.charset)
self.cur = self.db.cursor() # 创建游标对象
def close(self): # 创建断开数据库链接 关闭游标函数
self.cur.close()
self.db.close()
def zhixing(self, sql, L=[]): # 创建pymysql.execute() 方法函数
try:
self.open() # 链接数据库
self.cur.execute(sql, L) # 参数化执行SQL命令
self.db.commit() # 提交数据
print("ok")
except Exception as e:
self.db.rollback() # 出错取消提交
print("Failed", e)
self.close() # 断开数据库链接 关闭游标
def all(self, sql, L=[]):
try:
self.open()
self.cur.execute(sql, L)
result = self.cur.fetchall()
return result
except Exception as e:
print("Failed", e)
self.close()
# frist.py
from mysqlpython import MysqlPython
# 创建数据库链接
sqlh = MysqlPython("db4")
# 创建数据库对象
sql_update = "update sheng set s_name='辽宁省'\
where s_name='云南省';"
# 调用xiugai函数 执行SQL命令:sql_update
sqlh.zhixing(sql_update)
sql_select = "select * from sheng where id=%s;"
# 调用all函数 执行SQL命令:sql_select
date = sqlh.all(sql_select, [1])
print(date)
用户登录系统示例:
from mysqlpython import Mysqlpython
from hashlib import sha1
uname = input("请输入用户名:")
pwd = input("请输入密码:")
# 用sha1给pwd加密
s1 = sha1() # 创建sha1加密对象
s1.update(pwd.encode("utf8")) # 指定编码
pwd2 = s1.hexdigest() # 返回16进制加密结果
sqlh = Mysqlpython("db4")
select = "select password from user where \
username=%s;"
result = sqlh.all(select, [uname])
# print(result)
# (('7c4a8d09ca3762af61e59520943dc26494f8941b',),)
if len(result) == 0:
print("用户名不存在")
elif result[0][0] == pwd2:
print("登录成功")
else:
print("密码错误")
# 创建一张表
# 连接数据库的模块
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
engine = create_engine("mysql+pymysql://root:123456@localhost/db4", encoding="utf8")
Base = declarative_base() # orm基类
class User(Base): # 继承Base基类
__tablename__ = "t123"
id = Column(Integer, primary_key=True)
name = Column(String(20))
address = Column(String(40))
Base.metadata.create_all(engine)