zoukankan      html  css  js  c++  java
  • Python连接MySQL数据库之pymysql模块使用

    前言:python 3.x版本连接数据库,使用的是mysql库,而python 2.x 版本是用的mysqldb库

    1、安装数据库:pip install pymysql  

    2、连接数据库,执行sql获取返回结果 写法一:

    import pymysql
    
    #连接数据库
    cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
    
    # 使用cursor()方法获取操作游标
    cursor = cnn.cursor()
    print("Connect DB successfully!")
    
    #准备执行的sql
    sql = "SELECT * FROM `uc_alias` where type=1 and id = 110137"
    try:
       # 执行SQL语句
       cursor.execute(sql)
       # 获取所有记录列表
       results = cursor.fetchall()
       for row in results:
          id = row[0]
          type = row[1]
          appid = row[2]
          info = row[3]
          token = row[4]
          ext = row[5]
          unionid = row[7]
          state = row[8]
          ctime = row[9]
          atime = row[10]
    
          # 打印结果
          print("id=%s,type=%s,appid=%s,info=%s,token=%s,ext=%s,unionid=%s,state=%s,ctime=%s,atime=%s" %(id, type, appid, info, token,ext, unionid, state, ctime,atime))
    except:
       print("Error: unable to fecth data")
       
    # 关闭光标对象
    cursor.close()
    #关闭数据库连接
    cnn.close()

    运行的结果:

    3、执行aql获取单条数据结果,写法二

    import pymysql
    
    #连接数据库
    cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
    
    # 使用cursor()方法获取操作游标
    cursor = cnn.cursor()
    print("Connect DB successfully!")
    
    #准备执行的sql
    sql = "SELECT * FROM `uc_alias` where type=1 and id = 110137"
    cursor.execute(sql)
    #获取单条查询的结果
    ret = cursor.fetchone()
    
    # 关闭光标对象
    cursor.close()
    #关闭数据库连接
    cnn.close()
    print(ret)

    运行结果只有条:

    3、执行aql获取多条数据结果

    import pymysql
    
    #连接数据库
    cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
    
    # 使用cursor()方法获取操作游标
    cursor = cnn.cursor()
    print("Connect DB successfully!")
    
    #准备执行的sql
    sql = "SELECT * FROM `uc_alias` where ctime between 1496739700 and 1496739720"
    cursor.execute(sql)
    #获取多条查询的结果
    ret = cursor.fetchall()
    
    # 关闭光标对象
    cursor.close()
    #关闭数据库连接
    cnn.close()
    print(ret)

    运行结果有多条:

  • 相关阅读:
    【学习笔记】Hibernate关联映射(Y2-1-6)
    百度搜索排名API接口返回JSON数据格式
    HtmlAgilityPack 属性获取
    HtmlAgilityPack
    HighCharts实现双Y轴
    QQ在线客服配置
    项目管理者必知:适用于仪表盘项目的7个优秀JavaScript库
    极简Node教程-七天从小白变大神(二:中间件是核心)
    极简Node教程-七天从小白变大神(一:你需要Express)
    CSS滚动插件
  • 原文地址:https://www.cnblogs.com/guo2733/p/10551077.html
Copyright © 2011-2022 走看看