1、安装pymysql库
准备,pymysql 库 pip3 instal pymysql
2、coonect 对象
1、创建与数据库连接的对象(调用 connect()方法 )
conn = pymysql.connect(参数列表)
1、host:主机地址
2、port:端口3306
3、passwd:密码
4、charset:编码方式,推荐utf8
5、user:用户名
2、连接对象 conn 的方法
1、close() 关闭连接
2、commit()提交到数据库执行
3、rollback()回滚
4、cursor() 创建游标对象,用于执行sql语句
3、游标对象
1、作用:执行sql语句
2、用法:cur = conn.cursor() cur.execute(SQL语句)
3、常用方法:
execute(sql命令,[sql语句部位元素]) 执行sql命令
fetchone() 获取结果集第一条记录
fetchmany(n) 获取n条记录
fetchall() 获取所有记录
3、pymysql使用流程
1、建立数据库连接 conn = pymysql.connect(..........)
2、创建游标对象 cur = conn.cursor()
3、执行sql语句 cur.execute("sql语句")
4、提交:conn.commit( )
5、关闭游标 cur.close()
6、断开连接 conn.close()
#1、导入pymysql包
import pymysql
#2、创建数据库连接对象
db = pymysql.connect(host="localhost",user="root",
passwd="105115",db="sg")
#3、使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
#4、使用excute()方法执行SQL查询
cursor.execute("insert into.. sg")
#5、提交到数据库执行
db.commit()
#6、关闭游标和数据库连接
cursor.close()
db.close()
4、参数占位
#sql语句的参数占位
name = input("请输入省:")
s_id = input("请输入该省的编号:")
sql = "insert into sheng(s_id,s_name) values(%s,%s)"
#无论是什么数据类型都用%s
cur.execute(sql,[s_id,name])#第二个参数必须为列表
5、数据库操作进行封装
from pymysql import *
class Mysqlpython:
def __init__(self,user,passwd,db,
host="localhost",port=3306,charset="utf8"):
self.user = user
self.passwd = passwd
self.db = db
self.host = host
self.port = port
self.charset = charset
def open(self):
self.conn = connect(user = self.user,passwd = self.passwd,
db = self.db, host = self.host,
port = self.port, charset = self.charset)
self.cursor = self.conn.cursor()
def close(self):
self.cursor.close()
self.conn.close()
def execut(self,sql):
self.open()
try:
print(type(sql))
self.cursor.execute(sql)
self.conn.commit()
print("执行成功")
except Exception as e:
self.conn.rollback()
print("失败",e)
self.close()
6、ER模型(Entry-Relationship)
1、定义: 实体--关系模型,用于数据库设计
2、三个概念
实体(矩形框)
属性(椭圆)
关系(实体之间的关系)
1、一对一关系(1:1): 夫妻对应
2、一对多关系(1:n):父亲对孩子
3、多对多关系(m:n):兄弟姐妹对兄弟姐妹
3、