一、准备MySQL数据
-- 创建 "京东" 数据库
create database jing_dong charset=utf8;
-- 使用 "京东" 数据库
use jing_dong;
-- 创建一个商品goods数据表
create table goods(
id int unsigned primary key auto_increment not null,
name varchar(150) not null,
cate_name varchar(40) not null,
brand_name varchar(40) not null,
price decimal(10,3) not null default 0,
is_show bit not null default 1,
is_saleoff bit not null default 0
);
-- 向goods表中插入数据
insert into goods values(0,'r510vc 15.6英寸笔记本','笔记本','华硕','3399',default,default);
insert into goods values(0,'y400n 14.0英寸笔记本电脑','笔记本','联想','4999',default,default);
insert into goods values(0,'g150th 15.6英寸游戏本','游戏本','雷神','8499',default,default);
insert into goods values(0,'x550cc 15.6英寸笔记本','笔记本','华硕','2799',default,default);
insert into goods values(0,'x240 超极本','超级本','联想','4880',default,default);
insert into goods values(0,'u330p 13.3英寸超极本','超级本','联想','4299',default,default);
insert into goods values(0,'svp13226scb 触控超极本','超级本','索尼','7999',default,default);
insert into goods values(0,'ipad mini 7.9英寸平板电脑','平板电脑','苹果','1998',default,default);
insert into goods values(0,'ipad air 9.7英寸平板电脑','平板电脑','苹果','3388',default,default);
insert into goods values(0,'ipad mini 配备 retina 显示屏','平板电脑','苹果','2788',default,default);
insert into goods values(0,'ideacentre c340 20英寸一体电脑 ','台式机','联想','3499',default,default);
insert into goods values(0,'vostro 3800-r1206 台式电脑','台式机','戴尔','2899',default,default);
insert into goods values(0,'imac me086ch/a 21.5英寸一体电脑','台式机','苹果','9188',default,default);
insert into goods values(0,'at7-7414lp 台式电脑 linux )','台式机','宏碁','3699',default,default);
insert into goods values(0,'z220sff f4f06pa工作站','服务器/工作站','惠普','4288',default,default);
insert into goods values(0,'poweredge ii服务器','服务器/工作站','戴尔','5388',default,default);
insert into goods values(0,'mac pro专业级台式电脑','服务器/工作站','苹果','28888',default,default);
insert into goods values(0,'hmz-t3w 头戴显示设备','笔记本配件','索尼','6999',default,default);
insert into goods values(0,'商务双肩背包','笔记本配件','索尼','99',default,default);
insert into goods values(0,'x3250 m4机架式服务器','服务器/工作站','ibm','6888',default,default);
insert into goods values(0,'商务双肩背包','笔记本配件','索尼','99',default,default);
二、SQL演练
1、将查询结果插入到另一张表中
(1)、创建商品分类表
-- 创建商品分类表
create table if not exists goods_cates(
id int unsigned primary key auto_increment,
name varchar(40) not null
);
(2)、查询goods中的所有商品种类
select cate_name from goods group by cate_name;
(3)、将查询结果插入到商品分类表中
insert into goods_cates (name) select cate_name from goods group by cate_name;
2、根据商品分类表中的数据更新商品表数据
update goods as g inner join goods_cates as c on g.cate_name=c.name set g.cate_name=c.id;
3、修改商品表中的字段并且和商品分类表关联
(1)、修改表字段
alter table goods change cate_name cate_id int unsigned not null;
(2)、关联外键
alter table goods add foreign key (cate_id) references goods_cates(id);
4、创建商品品牌表的同时插入数据
create table goods_brands (
id int unsigned primary key auto_increment,
name varchar(40) not null)
select brand_name as name from goods group by brand_name;
5、取消表中关联的外键
-- 需要先获取外键约束名称,该名称系统会自动生成,可以通过查看表创建语句来获取名称
show create table goods;
-- 获取名称之后就可以根据名称来删除外键约束
alter table goods drop foreign key 外键名称;
三、Python与MySQL交互
1、ubuntu中安装pymysql模块
root@ubuntu:/# pip install pymysql
2、Python中操作MySQL步骤
3、引入模块
在.py文件中引入pymysql模块
from pymysql import *
4、Connection对象
(1)、作用
用于创建与数据库的链接
(2)、创建Connection对象
conn=connect(参数列表)
参数host:连接的mysql主机ip,如果本机是'localhost'
参数port:连接的mysql主机的端口,默认是3306
参数database:数据库的名称
参数user:连接的用户名
参数password:连接的密码
参数charset:通信采用的编码方式,推荐使用utf8
(3)、对象的方法
close()关闭连接
commit()提交
rollback()回滚
cursor()返回Cursor对象,用于执行sql语句并获得结果
5、Cursor对象
(1)、作用
用于执行sql语句,使用频度最高的语句为select、insert、update、delete
获取Cursor对象:调用Connection对象的cursor()方法
(2)、创建对象的方法
cs1=conn.cursor()
(3)、cursor对象的API
close()关闭
execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
(4)、cursor对象的属性
rowcount只读属性,表示最近一次execute()执行后受影响的行数
connection获得当前连接对象
6、简单的增加、查询案例
from pymysql import connect
class JD(object):
def __init__(self):
# 创建链接
self.conn = connect(host='192.168.37.128', port=3306, user='root', password='admin123', database='jing_dong',
charset='utf8')
# 获取cursor对象
self.cursor = self.conn.cursor()
def __del__(self):
# 关闭cursor对象
self.cursor.close()
self.conn.close()
def execute_sql(self,sql):
self.cursor.execute(sql)
# 遍历数据
for good in self.cursor.fetchall():
print(good)
def show_all_goods(self):
"""显示所有商品"""
# 编写sql
sql = "SELECT * FROM goods"
# 执行sql
self.execute_sql(sql)
def show_all_cates(self):
# 编写sql
sql = "select * from goods_cates"
self.execute_sql(sql)
def insert_goods(self):
cate = input("请输入要添加的分类名称")
sql = """insert into goods_cates(name) values("%s")""" % cate
# 执行sql
self.cursor.execute(sql)
self.conn.commit()
@staticmethod
def print_menu():
print("---------- welcome to JD ----------")
print("1:查询所有商品")
print("2:查询所有商品分类")
print("3:查询所有商品品牌")
return input("---------- 请输入功能对应的序号 ----------")
def run(self):
while True:
num = self.print_menu()
if num == "1":
# 查询所有商品
self.show_all_goods()
elif num == "2":
# 查询所有分类
self.show_all_cates()
elif num == "3":
# 添加商品
self.insert_goods()
def main():
# 1.创建一个京东商城对象
jd = JD()
# 2.调用这个对象的run方法,让其运行
jd.run()
if __name__ == "__main__":
main()
7、防止SQL注入的添加
from pymysql import connect
class JD(object):
def __init__(self):
# 创建链接
self.conn = connect(host='192.168.37.128', port=3306, user='root', password='admin123', database='jing_dong',
charset='utf8')
# 获取cursor对象
self.cursor = self.conn.cursor()
def __del__(self):
# 关闭cursor对象
self.cursor.close()
self.conn.close()
def run(self):
find_name = input("请输入要查询的商品名称:")
sql = "select * from goods where name = %s"
"""
将查询的参数放入列表中,使用execute的带2个参数的方法执行查询,即可以防止sql注入问题
"""
param = [find_name]
self.cursor.execute(sql, param)
for temp in self.cursor.fetchall():
print(temp)
def main():
# 1.创建一个京东商城对象
jd = JD()
# 2.调用这个对象的run方法,让其运行
jd.run()
if __name__ == "__main__":
main()