zoukankan      html  css  js  c++  java
  • Python学习第二十六课——PyMySql(python 链接数据库)

    Python 链接数据库:

    需要先安装pymysql 包 可以设置中安装,也可以pip install pymysql 安装

    加载驱动:

    import pymysql  # 需要先安装pymysql 包  可以设置中安装,也可以pip install pymysql 安装
    
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123123', db='s3')  # 加载驱动
    
    #cursor = conn.cursor()  # 创建游标
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 创建游标  查询到的数据以字典的形式显示

    执行操作1:

    #执行sql语句————创建表
    
    sql='CREATE TABLE test (id TINYINT, name VARCHAR(25))'
    cursor.execute(sql)

    执行操作2:

    #执行sql语句————添加表数据
    sql1 = 'insert into test values(1,"hh"),(2,"meimei")'
    ret = cursor.execute(sql1)
    print(ret)  # 2  成功添加两条数据

    执行操作3:

    # 执行sql语句————查询表数据
    sql2 = 'select * from test'
    ret1=cursor.execute(sql2)
    print(ret1) # 4  查询出来数据一共多少条
    result1 = cursor.fetchone()  # (1, 'hh') 具体数据的第一条
    result2 = cursor.fetchall()  #  ((1, 'hh'), (1, 'hh'), (1, 'hh'), (2, 'meimei')) 全部具体数据
    result3 = cursor.fetchmany(2) # ((1, 'hh'), (1, 'hh')) 查询具体数据前两条
    print(result1)
    print(result2)
    print(result3)

    最后执行更新和关闭操作:

    conn.commit();  # 更新数据
    cursor.close();  # 关闭
    conn.close()  # 关闭
  • 相关阅读:
    hdu 2647 Reward
    hdu 2094 产生冠军
    hdu 3342 Legal or Not
    hdu 1285 确定比赛名次
    hdu 3006 The Number of set
    hdu 1429 胜利大逃亡(续)
    UVA 146 ID Codes
    UVA 131 The Psychic Poker Player
    洛谷 P2491消防 解题报告
    洛谷 P2587 [ZJOI2008]泡泡堂 解题报告
  • 原文地址:https://www.cnblogs.com/pyhan/p/12342346.html
Copyright © 2011-2022 走看看