zoukankan      html  css  js  c++  java
  • pymysql

     - Pip 安装 pymysql

    pip install pymysql  

     - 简单查询

    import pymysql # 导入pymysql
    
    mysql_conn = pymysql.connect(host="127.0.0.1",  # 连接数据库
                                 port=3306,
                                 user="root",
                                 password="",
                                 charset="utf8",
                                 db="userinfo")
    c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor) # cursor获取操作游标,DictCursor以字典形式输出,默认是元组
    
    sql = "select * from users WHERE name='小黑' and age=17" # sql语句  users 数据库表名c.execute(sql) # 执行sql语句
    
    c.execute(sql)
    print(c.fetchall()) # 获取所有记录 c.close() # 关闭连接 mysql_conn.close()

     - 结果

    [{'id': 2, 'name': '小黑', 'age': 17}]

     - 简单插入

    import pymysql
    
    mysql_conn = pymysql.connect(host="127.0.0.1",
                                 port=3306,
                                 user="root",
                                 password="",
                                 charset="utf8",
                                 db="userinfo")
    c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    
    sql = "insert into users(id,name,age) value(4,'小王',20) "
    
    c.execute(sql)
    
    mysql_conn.commit()
    
    c.close()
    mysql_conn.close()

     - 更新

    import pymysql
    
    mysql_conn = pymysql.connect(host="127.0.0.1",
                                 port=3306,
                                 user="root",
                                 password="",
                                 charset="utf8",
                                 db="userinfo")
    c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    
    sql = "update users set name ='%s' where id = %d"
    
    c.execute(sql % ("小红",4))
    
    mysql_conn.commit()
    
    c.close()
    mysql_conn.close()

     - 删除

    import pymysql
    
    mysql_conn = pymysql.connect(host="127.0.0.1",
                                 port=3306,
                                 user="root",
                                 password="",
                                 charset="utf8",
                                 db="userinfo")
    c = mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    
    sql = "delete from users where id = %d"
    
    c.execute(sql % (4))
    
    mysql_conn.commit()
    
    c.close()
    mysql_conn.close()

  • 相关阅读:
    PAT 甲级 1128 N Queens Puzzle
    HDU 1995 R-汉诺塔V
    PAT L1-039 古风排版
    PAT L2-028 秀恩爱分得快
    ZOJ 2060 A-Fibonacci Again
    HDU 2079 选课时间
    HDU 1016 Prime Ring Problem
    理论相关概念原理
    单播字符、字符串收发
    OSAL的原理
  • 原文地址:https://www.cnblogs.com/lzmdbk/p/10269042.html
Copyright © 2011-2022 走看看