Python-MySQL练习

在Pycharm中执行MySQL指令

1.查询goods表中,id不小于4的商品信息  

#coding=utf-8
from pymysql import * def main():   #创建connecton连接
  conn=connect(host='localhost',port=3306,user='root',password='zhouyl1992',database='market',charset='utf8')   #创建Cursor对象   cs1=conn.cursor()   #进行查询操作,并返回受影响的行数   count=cs1.execute('select id,name from goods where id >= 4')   print('查询到%d条数据'%count)   #打印出所有查询到的数据   for i in range(count):     result=cs1.fetchone()     print(result)   #关闭   cs1.close()   conn.close() if __name__=='__main__':   main()

 2.用面向对象的思想进行增删改操作

# coding=utf-8
from pymysql import *


# 用面向对象的思想来实现sql
class JD(object):
    def __init__(self):
        # 创建connect连接
        self.conn = connect(host='localhost', port=3306, user='root', password='zhouyl1992', database='jingdong',
                            charset='utf8')
        self.cs1 = self.conn.cursor()

    def __del__(self):
        # 关闭连接
        self.cs1.close()
        self.conn.close()

    def cs_fetchall(self, sql):
        self.cs1.execute(sql)
        for temp in self.cs1.fetchall():
            print(temp)

    # 查询所有商品
    def show_all_items(self):
        sql = 'select * from goods;'
        self.cs_fetchall(sql)

    # 查询所有商品分类
    def show_cates(self):
        sql = 'select name from goods_cates;'
        self.cs_fetchall(sql)

    # 查询所有商品品牌
    def show_brands(self):
        sql = 'select name from goods_brands;'
        self.cs_fetchall(sql)

    def add_cates(self):
        cate_name=input('输入商品分类名称:')
        sql='insert into goods_cates(name) values("%s")'%cate_name
        self.cs1.execute(sql)
        self.conn.commit()

    def run(self):
        while True:
            print('----京东商城----')
            print('1.所有的商品')
            print('2.所有商品分类')
            print('3.所有商品品牌')
            print('4.添加商品分类')
            print('5.退出')
            num = input('请输入操作对应的数字:')

            if num == '1':
                self.show_all_items()
            elif num == '2':
                self.show_cates()
            elif num == '3':
                self.show_brands()
            elif num == '4':
                self.add_cates()
            elif num == '5':
                break
            else:
                print('输入的数字错误,请重新输入')


def main():
    # 1.创建一个京东商城对象
    jd = JD();
    # 2.调用这个对象的run方法,让其运行
    jd.run()


if __name__ == '__main__':
    main()

 

3.商品分类数据进行新增,修改,删除

  对表中数据进行增删改操作,execute执行后一定要进行commit提交操作,否则之前的操作都不会生效

#coding=utf-8
from pymysql import *
def main():
    # 创建connection连接
    conn=connect(host='localhost', port=3306, user='root', password='zhouyl1992', database='jingdong',
                            charset='utf8')
    # 获得Cursor对象
    cs=conn.cursor()
    # 执行sql语句,并返回受影响的行数
    cs.execute("""insert into goods_cates(name) values ('硬盘-new')""")
    cs.execute('update goods_cates set name = "硬盘2-new" where name="硬盘-new"')
    cs.execute('delete from goods_cates where id=13')
    cs.execute('select * from goods_cates;')
    for temp in cs.fetchall():
        print(temp)
    #提交之前的操作,如果执行多次的execute,那么就都进行提交
    conn.commit()

  
#对之前提交的操作进行回滚操作,commit后不能回滚
  #conn.rollback()
  # 关闭Cursor对象  
  cs.close()
  conn.close()

if
__name__ == '__main__':
  main()

4.防止sql注入

# coding=utf-8
#防止sql注入

from pymysql import *


def main():
    # 创建connection连接
    conn = connect(host='localhost', port=3306, user='root', password='zhouyl1992', database='jingdong',
                   charset='utf8')
    # 获得Cursor对象
    cs = conn.cursor()
    find_name = input('请输入查询商品的名称:')
    ##非安全的方式
    ##输入"or 1=1 or 1"(双引号也要输入)
    # sql='select * from goods where name="%s"'%find_name
    # print("""sql====>%s<===="""%sql)
    # #执行select语句,并返回受影响的行数,查询所有数据
    # count=cs.execute(sql)

    # 安全的方式
    # 构造参数列表
    params = [find_name]
    # 执行select语句,并返回受影响的行数,查询所有数据
    count = cs.execute('select * from goods where name=%s', params)
    # 注意:
    # 如果有多个参数,需要进行参数化
    # 那么params=[数值1,数值2...]此时sql语句中有多个%s即可

    # 打印受影响的行数
    print(count)
    # 获取查询的结果
    result = cs.fetchall()
    # 打印查询的结果
    print(result)
    # 关闭游标和连接
    cs.close()
    conn.close()


if __name__ == '__main__':
    main()

 

posted @ 2020-08-10 17:22  zhou&zhou  阅读(202)  评论(0)    收藏  举报