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)

    运行结果有多条:

  • 相关阅读:
    转:高并发高负载系统架构
    用java模拟银行柜台排队
    转:VS2010与SVN
    转:MySQL导入.sql文件及常用命令
    转:Mongodb中随机的查询文档记录
    转:Thumbs.db是什么文件?是病毒吗?怎么处理?
    转:OWASP发布Web应用程序的十大安全风险
    转:Top 10 Algorithms for Coding Interview
    编写C# Windows服务,用于杀死Zsd.exe进程
    转:eclipse载入extjs4出现内存溢出错误的解决方法
  • 原文地址:https://www.cnblogs.com/guo2733/p/10551077.html
Copyright © 2011-2022 走看看