• python使用MySQLdb实现连接数据库Mysql


    python实现连接数据库mysql的步骤:

    一、引入MySQLdb

    二、获取与数据库的连接

    三、执行SQL语句和存储过程

    四、关闭数据库连接

     

    1.什么是MySQLdb?

    MySQLdb是用于python连接mysql数据库的接口;

    2.连接数据库前确认事项:

    (1)数据库名:testdb

    (2)数据库的用户名:root  密码为:123456

    (3)数据库IP:127.0.0.1

    (4)数据库端口:3306

    (5)查询数据库tablename表的记录数

    3.给出代码

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    
    # 打开数据库连接
    db = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='testsb', charset='utf8' )
    
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
    sql = """select count(*) from tablename;"""
    # 使用execute方法执行SQL语句 
    cursor.execute(sql)
    # 使用 fetchone() 方法获取一条数据
    data = cursor.fetchone()

    print "Database version : %s " % data

    # 关闭数据库连接
    db.close()

    4.或者是:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import MySQLdb as mdb
    
    # 连接数据库
    # conn = mdb.connect('localhost', 'root', 'root')
    
    # 也可以使用关键字参数
    conn = mdb.connect(host="127.0.0.1",port=3306,user='root',passwd='123456',db='testdb',charset='utf8')

    # # 也可以使用字典进行连接参数的管理
    #
    config = { # 'host': '127.0.0.1',
    #
    'port': 3306,
    #
    'user': 'root',
    #
    'passwd': 'root',
    #
    'db': 'test',
    #
    'charset': 'utf8'
    #
    }
    #
    conn = mdb.connect(**config)

    # 如果使用事务引擎,可以设置自动提交事务,或者在每次操作完成后手动提交事务conn.commit()
    conn.autocommit(1)

    # conn.autocommit(True)

    # 使用cursor()方法获取操作游标
    cursor = conn.cursor()

    # 因该模块底层其实是调用CAPI的,所以,需要先得到当前指向数据库的指针。
    TABLE_NAME
    = 'bsj'
    try:
      sql
    = """select count(*) from vehicle;"""
      cursor.execute(sql)
      # 返回单个的元组,也就是一条记录(row),如果没有结果则返回None
      result
    =cursor.fetchone()

      print(result)

      # 如果没有设置自动提交事务,则这里需要手动提交一次
      conn.commit()

    except:
      import traceback 
      traceback.print_exc()

      # 发生错误时会滚
      conn.rollback()

    finally:
      
    # 关闭游标连接
      cursor.close()

      # 关闭数据库连接
      conn.close()

    5.注意事项:

    如果select本身取的时候有多条数据时:

    cursor.fetchone():将只取最上面的第一条结果,返回单个元组如('id','title'),然后多次使用cursor.fetchone(),依次取得下一条结果,直到为空。

    cursor.fetchall() :将返回所有结果,返回二维元组,如(('id','title'),('id','title')),
    ---------------------

    如果select本身取的时候只有一条数据时:

    cursor.fetchone():将只返回一条结果,返回单个元组如('id','title')。

    cursor.fetchall() :也将返回所有结果,返回二维元组,如(('id','title'),)

    备注:其中的id和title为具体的内容

    python在mysql在使用fetchall或者是fetchone时,综合起来讲,fetchall返回二维元组(元组中含有元组),fetchone只返回一维元组。

     

    6.MySQLsb默认查询结果都是返回元组(tuple),通过使用不同的游标可以改变输出格式,这里传递一个cursors.DictCursor参数

    import MySQLdb.cursors
    
    conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', cursorclass=MySQLdb.cursors.DictCursor)
    cursor = conn.cursor()
    sql = """select count(*) from tablename;"""
    cursor.execute(sql)
    r = cursor.fetchall()
    print(r)
    # 当使用位置参数或字典管理参数时,必须导入MySQLdb.cursors模块
    
    # 也可以用下面的写法
    import MySQLdb as mdb
    conn  = mdb.connect('127.0.0.1', 'root', '123456', 'testdb')
    cursor = conn.cursor(cursorclass=mdb.cursors.DictCursor)
    sql = """select count(*) from tablename;"""
    cursor.execute(sql)
    r = cursor.fetchall()
    print(r)

    使用MySQLdb取回大结果集的缺点:

    普通的操作无论是fetchall()还是fetchone()都是先将数据载入到本地再进行计算,大量的数据会导致内存资源消耗光。

    解决方法:

     
  • 相关阅读:
    【uiautomator】Interfaces+Exception
    【uiautomator】UiDevice
    【uiautomator】Uiautomator API
    【uiautomator】运行命令
    [www.infoshare.cc]【uiautomator】输入中文(输入法安装+测试代码)
    MFC ,List使用
    VC控件DateTimePicker使用方法
    GitHub vs. Bitbucket 不只是功能不同
    免费的私人代码托管(bitbucket) 和 常用git指令
    修改android studio中的avd sdk路径、avd sdk找不到的解决方案
  • 原文地址:https://www.cnblogs.com/yfacesclub/p/10418367.html
Copyright © 2020-2023  润新知