【转】python数据库编程, pymysql, Connect, cursor, commit, rollback , fetchall

转载自:https://blog.csdn.net/vivian_wanjin/article/details/82778589

import pymysql


class JD(object):
    def __init__(self):
        self.dic = {0: self.__close,
                    1: self.__fetch_all_info,
                    2: self.__fetch_cate,
                    3: self.__fetch_brand,
                    4: self.__add_info,
                    5: self.__find_info,
                    6: self.__find_info_safe
                    }
         # user,和password换成你的root和密码
        self.__conn = pymysql.Connect(host="localhost",
                                      port=3306,
                                      database="JDDB",
                                      user="demouser",
                                      password="demopassword",
                                      charset="utf8")
        self.__cur = self.__conn.cursor()

    def __show_result(self, result):
        # print(type(result))   # <cass 'tuple'>
        for r in result:
            print(r)

    # 查询所有商品信息
    def __fetch_all_info(self):
        sql = ''' select * from goods '''
        affected = self.__cur.execute(sql)
        print("influenced %d row" % affected)
        self.__show_result(self.__cur.fetchall())

    # 查询种类信息
    def __fetch_cate(self):
        sql = ''' select * from goods_cates '''
        self.__cur.execute(sql)
        self.__show_result(self.__cur.fetchall())

    # 查询品牌信息
    def __fetch_brand(self):
        sql = ''' select * from goods_brands '''
        self.__cur.execute(sql)
        self.__show_result(self.__cur.fetchall())

    # 添加一个商品类型
    def __add_info(self):
        goods_type = input("please input a new goods type: ")
        sql = ''' insert into  goods_cates(name) values ("%s") '''
        self.__cur.execute(sql, goods_type)
        self.__conn.commit()

    # 通过ID 查找商品
    def __find_info(self):
        # 当输入 "id or True" 时会发生sql注入,看到本不该看到的东西
        goods_type = input("please input a ID of cates: ")
        sql = ''' select * from goods where id=%s''' % goods_type
        self.__cur.execute(sql)
        self.__show_result(self.__cur.fetchall())

    # 通过ID 查找商品 防SQL注入
    def __find_info_safe(self):
        goods_type = input("please input a ID of cates: ")
        # 此处不同于python的字符串格式化,必须全部使用%s占位
        sql = ''' select * from goods where id=%s'''
        # 通过参数化列表(元组)防止这种攻击,但是会产生一个warning,可以直接存储到日志log中
        self.__cur.execute(sql, (goods_type,))
        self.__show_result(self.__cur.fetchall())
	# 关闭连接,退出
    def __close(self):
        self.__cur.close()
        self.__conn.close()
        exit()

    def run(self):
        while True:
            print('*' * 50)
            print("1查询所有商品信息")
            print("2查询所有商品在种类信息")
            print("3查询所有商品在品牌信息")
            print("4添加商品种类")
            print("5根据id查询商品信息")
            print("6根据id查询商品信息安全方式")
            print("0退出")
            print('*' * 50)

            option = int(input("please input your option: "))
            try:
                self.dic[option]()
                # string()  # eval()
            except KeyError:
                print("enter is error! ")


def main():
    jd = JD()
    jd.run()


if __name__ == '__main__':
    main()

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyMySQLPython下的一个MySQL驱动程序,实现了Python DB API v2.0 规范,并且支持Python3。下面是使用PyMySQL操作MySQL数据库的示例代码: 1. 安装PyMySQL 在终端中输入以下命令安装PyMySQL: ``` pip install pymysql ``` 2. 连接数据库 ```python import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="password", database="test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 关闭数据库连接 db.close() ``` 3. 创建表 ```python import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="password", database="test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 创建表 sql = """CREATE TABLE `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `age` int(11) NOT NULL, `sex` varchar(10) NOT NULL, `income` float NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8""" cursor.execute(sql) # 关闭数据库连接 db.close() ``` 4. 插入数据 ```python import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="password", database="test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 插入数据 sql = "INSERT INTO `employee`(`name`, `age`, `sex`, `income`) VALUES ('Tom', 25, 'Male', 5000.0)" cursor.execute(sql) # 提交事务 db.commit() # 关闭数据库连接 db.close() ``` 5. 查询数据 ```python import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="password", database="test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 查询数据 sql = "SELECT * FROM `employee` WHERE `age` > 20" cursor.execute(sql) # 获取查询结果 results = cursor.fetchall() for row in results: id = row[0] name = row[1] age = row[2] sex = row[3] income = row[4] print("id=%d,name=%s,age=%d,sex=%s,income=%.2f" % (id, name, age, sex, income)) # 关闭数据库连接 db.close() ``` 6. 更新数据 ```python import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="password", database="test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 更新数据 sql = "UPDATE `employee` SET `income` = `income` * 1.1 WHERE `age` > 20" cursor.execute(sql) # 提交事务 db.commit() # 关闭数据库连接 db.close() ``` 7. 删除数据 ```python import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="password", database="test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 删除数据 sql = "DELETE FROM `employee` WHERE `age` > 25" cursor.execute(sql) # 提交事务 db.commit() # 关闭数据库连接 db.close() ``` 以上就是使用PyMySQL操作MySQL数据库的示例代码。其中,db.commit()用于提交事务,如果不提交,则数据操作不会生效。如果有异常,则可以使用db.rollback()回滚事务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值