Python操作三大主流数据库

参考:https://www.cnblogs.com/JCcodeblgos/p/10331542.html


copy:

  • 网址:https://coding.imooc.com/learn/list/114.html
  • 学会使用的技术栈:python flask redis mongoDB mysql

3-3 python查询mysql数据库
 

# -- coding: utf-8 --
import MySQLdb

#中文输出. 只是为了在控制台上显示,字符的类型是正确的。
def chinese_output(str_tuple):
    for i in range(len(str_tuple)):
        print str_tuple[i]
    pass

#将获取链接封装成calss
class MysqlSearch(object):  # 让MysqlSearch类继承object对象

    def __init__(self): # 在初始化的时候调用
        self.get_conn()


    def get_conn(self): # 数据库链接
        try:
            self.conn = MySQLdb.connect(
                host = "127.0.0.1",
                user = "root",
                passwd = "admin123",
                db = "news",
                port = 3306,
                charset = 'utf8'
                )
        except MySQLdb.Error as e:
            print "Error : %s" % e

    def close_conn(self):   #关闭数据库
        try:
            if self.conn:
                # 关闭链接
                self.conn.close()
        except MySQLdb.Error as e:
            print "Error: %s" % e

    def get_one(self): #查询一条数据
        """ 流程:"""
        # 1.准备SQL
        sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
        # 2.找到cursor
        cursor = self.conn.cursor()
        # 3.执行SQL
        cursor.execute(sql, ("本地", ))
         # 这边传的参数是一个元组
        # print cursor.rowcount # 一共多少行 
        # print cursor.description
        # 4.拿到结果
        # rest = cursor.fetchone() # 就查询一体哦啊结果
        rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
        # 5.处理数据
        #print rest
        #print rest['title']
        # 6.关闭cursor链接  两个关闭
        cursor.close()
        self.close_conn() 

        return rest

    def get_more(self):
        sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
        cursor = self.conn.cursor()
        cursor.execute(sql, ("本地", ))
        # 多条数据获取的应该是一个list
        # 列表推倒式子
        rest = [dict(zip([k[0] for k in cursor.description], row)) 
            for row in cursor.fetchall() ]
        cursor.close()
        self.close_conn()
        return rest


    # 多条数据换页 
    def get_more_page(self, page, page_size):
        # 页面换算
        offset = (page - 1) * page_size # 启始页面

        sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s, %s;'
        cursor = self.conn.cursor()
        # 将数字转换为字符.  不用转换。 瞎忙活。 
        # offset_str = str(offset)
        # page_size_str = str(page_size)

        cursor.execute(sql, ('本地', offset, page_size, ))
        # 多条数据获取的应该是一个list
        # 列表推倒式子
        rest = [dict(zip([k[0] for k in cursor.description], row)) 
            for row in cursor.fetchall() ]
        cursor.close()
        self.close_conn()
        return rest

def main():
    obj = MysqlSearch()

    #单个结果输出
    rest = obj.get_one()
    print rest['title']

    #多个结果删除。list
    rest_more = obj.get_more()
    for item in rest_more:
        print item
        print '-----------------------------------------------------------------------'

    #分页输出 
    rest_more_page = obj.get_more_page(1,1)
    for item in rest_more_page:
        print item
        print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'

if __name__ == '__main__':
    main()

3-4 python更新mysql数据

# -- coding: utf-8 --
import MySQLdb

#中文输出. 只是为了在控制台上显示,字符的类型是正确的。
def chinese_output(str_tuple):
    for i in range(len(str_tuple)):
        print str_tuple[i]
    pass

#将获取链接封装成calss
class MysqlSearch(object):  # 让MysqlSearch类继承object对象

    def __init__(self): # 在初始化的时候调用
        self.get_conn()


    def get_conn(self): # 数据库链接
        try:
            self.conn = MySQLdb.connect(
                host = "127.0.0.1",
                user = "root",
                passwd = "admin123",
                db = "news",
                port = 3306,
                charset = 'utf8'
                )
        except MySQLdb.Error as e:
            print "Error : %s" % e

    def close_conn(self):   #关闭数据库
        try:
            if self.conn:
                # 关闭链接
                self.conn.close()
        except MySQLdb.Error as e:
            print "Error: %s" % e

    def get_one(self): #查询一条数据
        """ 流程:"""
        # 1.准备SQL
        sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
        # 2.找到cursor
        cursor = self.conn.cursor()
        # 3.执行SQL
        cursor.execute(sql, ("本地", ))
         # 这边传的参数是一个元组
        # print cursor.rowcount # 一共多少行 
        # print cursor.description
        # 4.拿到结果
        # rest = cursor.fetchone() # 就查询一体哦啊结果
        rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
        # 5.处理数据
        #print rest
        #print rest['title']
        # 6.关闭cursor链接  两个关闭
        cursor.close()
        self.close_conn() 

        return rest

    def get_more(self):
        sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
        cursor = self.conn.cursor()
        cursor.execute(sql, ("本地", ))
        # 多条数据获取的应该是一个list
        # 列表推倒式子
        rest = [dict(zip([k[0] for k in cursor.description], row)) 
            for row in cursor.fetchall() ]
        cursor.close()
        self.close_conn()
        return rest


    # 多条数据换页 
    def get_more_page(self, page, page_size):
        # 页面换算
        offset = (page - 1) * page_size # 启始页面

        sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s, %s;'
        cursor = self.conn.cursor()
        # 将数字转换为字符.  不用转换。 瞎忙活。 
        # offset_str = str(offset)
        # page_size_str = str(page_size)

        cursor.execute(sql, ('本地', offset, page_size, ))
        # 多条数据获取的应该是一个list
        # 列表推倒式子
        rest = [dict(zip([k[0] for k in cursor.description], row)) 
            for row in cursor.fetchall() ]
        cursor.close()
        self.close_conn()
        return rest

    def add_one(self):
        """事务处理"""
        try: 
            # 准备SQL
            sql =( 
                "INSERT INTO `news` (`title`, `image`, `content`, `types`, `is_valid`) VALUE "
                "( %s, %s, %s, %s, %s );"
            )
             # 出现换行的时候用一个元组扩起来。 应用双引号扩起来
            # 获取链接和cursor
            cursor = self.conn.cursor()
            # 执行SQL
            cursor.execute(sql, ('标题7','0122.png', '新闻内容22', '推荐', 1))
            cursor.execute(sql, ('标题8','0122.png', '新闻内容22', '推荐', 'ss'))
            # 错误
            # 提交数据到数据库
            """ 如果不提交的事务的话。就是 已经提交多数据库 但是没有被保存  """
            # 提交事务
self.conn.commit()
            # 关闭cursor
            cursor.close()
        except :
            print "Error"
            # self.conn.commit() # 部分提交
            self.conn.rollback() # 回滚
        # 关闭链接
        self.close_conn()    

# 多选 + / 多行注释

def main():
    obj = MysqlSearch()

    #单个结果输出
    # rest = obj.get_one()
    # print rest['title']

    #多个结果删除。list
    # rest_more = obj.get_more()
    # for item in rest_more:
    #     print item
    #     print '-----------------------------------------------------------------------'

    #分页输出 
    # rest_more_page = obj.get_more_page(1,1)
    # for item in rest_more_page:
    #     print item
    #     print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    obj.add_one()

if __name__ == '__main__':
    main()

本文:基本crud代码:https://www.cnblogs.com/JCcodeblgos/p/10331542.html

其他代码学习。gitHub地址:

 操作redis   https://github.com/stableMan/python-handle-Mysql_Redis_Mongodb 

  flask 操作redis 网易新闻实战  https://github.com/stableMan/flask_news 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值