zoukankan      html  css  js  c++  java
  • 数据库的连接-pymysql库的使用

    """
    数据库的步骤:
    1, 建立连接  ---> 认识小姐姐(加个微信)
    2, 得到一个游标的对象(数据库的操作都是通过游标), 你和小姐姐约会,见面的机会。
    3, execute(sql)  ,具体的而执行,(看电影)
    4, 获取执行 sql 语句的结果。  (反馈和结果)
    5, 关闭游标对象 (再见)
    6, 关闭链接。 (微信晚安)
    """
    import pymysql
    
    # 建立连接
    host = ''
    port = 3306
    username = ''
    password = ''
    db_name = ''
    
    # 1,得到连接对象
    connection = pymysql.connect(host=host,
                                 port=port,
                                 user=username,
                                 password=password,
                                 database=db_name)
    
    # 2, 获取游标对象, 就相当于读取数据库内容的时候光标
    cursor = connection.cursor()
    print(cursor)
    
    # 3, 执行 sql
    sql = 'select id, reg_name from member limit 5;'
    cursor.execute(sql)
    
    # 4, 获取结果 fetchone(), sql 语句查询的一条结果
    # 存储到元组中
    rows = cursor.fetchone()
    print(rows)
    
    # 4, 获取结果 fetchall(), sql 语句查询的多条结果
    # 存储到元组中
    
    # cursor2 = connection.cursor()
    # sql = 'select id, reg_name from member limit 5;'
    # cursor2.execute(sql)
    # rows = cursor2.fetchall()
    # print(rows)
    # 尽量避免使用一个游标进行多次操作。
    
    # 关闭游标
    cursor.close()
    # 关闭链接
    connection.close()
  • 相关阅读:
    洛谷P1057 传球游戏
    洛谷 CF937A Olympiad
    洛谷P4057 晨跑
    New blog
    DHTMLX系列组件的学习笔记
    javascript学习笔记
    typeof 使用介绍
    tomcat启动后ids页面无法访问
    快捷键accesskey
    jquery回调函数callback的使用
  • 原文地址:https://www.cnblogs.com/wsfsd/p/15469632.html
Copyright © 2011-2022 走看看