• ttttt
    2019-07-19
    import json
    import traceback
    import mysql.connector

    # 读取数据库链接配置文件
    with open('mysql.json', encoding='utf-8') as con_json:
        con_dict = json.load(con_json)

    # 打开数据库链接
    db = mysql.connector.connect(
        host=con_dict['host'],
        user=con_dict['user'],
        passwd=con_dict['passwd'],
        database=con_dict['database'],
        auth_plugin=con_dict['auth_plugin'],
    )

    # 获取操作游标
    cursor = db.cursor()
    try:
        sql = 'SELECT id, name, hp_max FROM heros WHERE hp_max>6000'
        cursor.execute(sql)
        data = cursor.fetchall()
        print(cursor.rowcount, '查询成功。')
        for each_hero in data:
            print(each_hero)
    except Exception as e:
        # 打印异常信息
        traceback.print_exc()
    finally:
        cursor.close()
        db.close()
    # 建议吧数据库链接信息写到配置文件里,防止密码泄露。
    展开

    作者回复: Good Job

    
     22
  • 一叶知秋
    2019-07-19
    sqlalchemy用习惯了。。。献丑来一段Python代码吧
    ```Python
    # -*- coding:utf-8 -*-
    from sqlalchemy import and_
    from sqlalchemy import Column, INT, FLOAT, VARCHAR
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    Base = declarative_base()


    class Test_db:
        def __init__(self):
            """此处填上自己的连接配置"""
            self.engine = create_engine(
                'mysql+pymysql://username:password@host:port/db_name?charset=utf8')
            db_session = sessionmaker(bind=self.engine)
            self.session = db_session()

        def query_all(self, target_class, query_filter):
            result_list = self.session.query(target_class).filter(query_filter).all()
            self.session.close()
            return result_list


    class Heros(Base):
        """定义表结构"""
        __tablename__ = 'heros'
        id = Column(INT(), primary_key=True)
        name = Column(VARCHAR(255))
        hp_max = Column(FLOAT())
        mp_max = Column(FLOAT())

        def __init__(self, id, name, hp_max, mp_max):
            self.id = id
            self.name = name
            self.hp_max = hp_max
            self.mp_max = mp_max


    if __name__ == '__main__':
        db_obj = Test_db()
        query_filter = and_(Heros.hp_max > 6000)
        heros = db_obj.query_all(Heros, query_filter)
        for hero_info in heros:
            print("id:{}, name:{}, hp_max:{}, mp_max:{}".format(hero_info.id, hero_info.name,
                                                                hero_info.hp_max, hero_info.mp_max))
    ```
    id:10000, name:夏侯惇, hp_max:7350.0, mp_max:1746.0
    id:10046, name:钟馗, hp_max:6280.0, mp_max:1988.0
    id:10048, name:鬼谷子, hp_max:7107.0, mp_max:1808.0
    id:10051, name:赵云, hp_max:6732.0, mp_max:1760.0
    id:10052, name:橘石京, hp_max:7000.0, mp_max:0.0
    id:10055, name:杨戬, hp_max:7420.0, mp_max:1694.0
    id:10056, name:达摩, hp_max:7140.0, mp_max:1694.0
    id:10057, name:孙悟空, hp_max:6585.0, mp_max:1760.0
    id:10058, name:刘备, hp_max:6900.0, mp_max:1742.0
    .....执行结果有点多字数限制了
    Process finished with exit code 0
    展开

    作者回复: Good Job

    
     5
  • Destroy、
    2019-07-19
    sql = 'DELETE FROM player WHERE name = %s'
    val = (" 约翰 - 科林斯 ")
    cursor.execute(sql)
    db.commit()
    print(cursor.rowcount, " 记录删除成功。")
    这里写错了哇,这样写才不会报错:
    sql = 'DELETE FROM player WHERE player_name = %s'
    val = (" 约翰 - 科林斯 ", )
    cursor.execute(sql, val)
    db.commit()
    print(cursor.rowcount, " 记录删除成功。")

    展开
     2
     3
  • mickey
    2019-07-19
    # -*- coding: UTF-8 -*-
    import mysql.connector
    import traceback

    # 打开数据库连接
    db = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="123456", # 写上你的数据库密码
        database='nba',
        auth_plugin='mysql_native_password'
    )

    # 获取操作游标
    cursor = db.cursor()

    try:

        # 查询heros 表中最大生命值大于 6000 的英雄进行查询,并且输出相应的属性值。
        sql = 'SELECT name, hp_max FROM heros WHERE hp_max > %s ORDER BY hp_max DESC'
        val = (6000,)
        cursor.execute(sql, val)
        data = cursor.fetchall()
        for each_player in data:
            print(each_player)
    except Exception as e:
      # 打印异常信息
      traceback.print_exc()
      # 回滚
      db.rollback()
    finally:
      # 关闭游标 & 数据库连接
      cursor.close()
      db.close()

    输出:

    ('廉颇', 9328.0)
    ('白起', 8638.0)
    ('程咬金', 8611.0)
    ('刘禅', 8581.0)
    ('牛魔', 8476.0)
    ('张飞', 8341.0)
    ('庄周', 8149.0)
    ('刘邦', 8073.0)
    ('项羽', 8057.0)
    ('亚瑟', 8050.0)
    ('东皇太一', 7669.0)
    ('典韦', 7516.0)
    ('曹操', 7473.0)
    ('杨戬', 7420.0)
    ('夏侯惇', 7350.0)
    ('吕布', 7344.0)
    ('哪吒', 7268.0)
    ('墨子', 7176.0)
    ('老夫子', 7155.0)
    ('达摩', 7140.0)
    ('鬼谷子', 7107.0)
    ('关羽', 7107.0)
    ('钟无艳', 7000.0)
    ('橘石京', 7000.0)
    ('刘备', 6900.0)
    ('太乙真人', 6835.0)
    ('孙膑', 6811.0)
    ('赵云', 6732.0)
    ('扁鹊', 6703.0)
    ('铠', 6700.0)
    ('露娜', 6612.0)
    ('孙悟空', 6585.0)
    ('钟馗', 6280.0)
    ('雅典娜', 6264.0)
    ('兰陵王', 6232.0)
    ('宫本武藏', 6210.0)
    ('娜可露露', 6205.0)
    ('高渐离', 6165.0)
    ('芈月', 6164.0)
    ('不知火舞', 6014.0)
    ('孙尚香', 6014.0)

    Process finished with exit code 0
    展开

    作者回复: Good Job

    
     3
  • 林彦
    2019-07-19
    try...except...那部分代码没有关闭游标的语句。关闭数据库连接的语句执行时一般都会先隐式关闭并释放当前的游标吗?
    
     2
  • 大斌
    2019-07-23
    核心代码:
    cursor = db.cursor()

    sql = "select name,hp_max from heros where hp_max > %s"
    val = (6000,)
    cursor.execute(sql,val)
    data = cursor.fetchall()
    注意:val里面的元素后面必须要加英文逗号,不加或者中文逗号都会报错
    展开

    作者回复: Good Job

    
     1
  • mickey
    2019-07-19
    sql = 'DELETE FROM player WHERE player_name = " 约翰-科林斯 "'
    
     1
  • 极客酱
    2019-07-19
    删除约翰·科林斯这个球员的数据代码里面,excute那个函数缺少了val的参数吧?
    
     1
  • 一步
    2019-07-19
    看目录,我以为到 SQL刷题了。。。
    
     1
  • 🤪HappyJoo
    2020-01-06
    还是想知道,为什么不直接用数据库管理工具呢?好像省了很多步骤,简单的update 一条数据,为什么要用python写那么多行代码呢?
    
    
  • taoist
    2019-12-19
    import pymysql
    import pymysql.cursors


    cfg = {
        "host": "127.0.0.1",
        "user": "root",
        "passwd": "toor",
        "database": "test",
        "charset": "utf8mb4",
        "autocommit": True,
        'cursorclass':pymysql.cursors.DictCursor
    }

    db_con = pymysql.connect(**cfg)

    try:
        with db_con.cursor() as cur:
            cur.execute("SELECT id,name,hp_max FROM heros WHERE hp_max > 6000 ")
            res = cur.fetchall()

        for i in res:
            print(i)
    finally:
        db_con.close()

    展开

    作者回复: 正确

    
    
  • 丁丁历险记
    2019-11-15
    当一些听着很虚的理论用于实战时,其威力是巨大的,例如信息的正交性。

    作者回复: 这种信息论的内容在机器学习中用的还是挺多的

     1
    
  • xcoder
    2019-09-04
    请问各路在线英雄,安装mysql-connector-python-8.0.17,那么对应的还是重新安装一个8.0.17的mysql了?这个有对老版本,比如5.6的mysql的支持吗?找了半天找不到,只有8.0版本的mysql才有的mysql-connector-python安装包吗?
     1
    
  • 胡
    2019-08-21
    -- >=2.08 插入的数据显示不出来

    __author__ = 'Administrator'

    # -*- coding: UTF-8 -*-
    import traceback
    import json
    import mysql.connector
    # 打开数据库连接
    db = mysql.connector.connect(
           host="localhost",
           user="root",
           passwd="hjf@2019", # 写上你的数据库密码
           database='nba',
           auth_plugin='mysql_native_password'
    )
    # 获取操作游标
    cursor = db.cursor()
    # 执行 SQL 语句
    #cursor.execute("SELECT VERSION()")
    # 获取一条数据
    #data = cursor.fetchone()
    #print("MySQL 版本: %s " % data)
    # 关闭游标 & 数据库连接



    # 插入新球员

    #sql = "INSERT INTO player (team_id,player_id,player_name,height) VALUES (%s, %s, %s,%s)"
    #val = (1003, 10038," 约翰 - 科林斯 ", 2.08)
    #cursor.execute(sql,val)
    #db.commit()
    #print(cursor.rowcount, " 记录插入成功。")


    # 查询身高大于等于 2.08 的球员
    sql = 'SELECT team_id, player_id, player_name, height FROM player WHERE height >=2.08'
    cursor.execute(sql)
    data = cursor.fetchall()
    for each_player in data:
      print(each_player)



    cursor.close()
    db.close()
    展开
    
    
  • 胡
    2019-08-21
    __author__ = 'Administrator'

    # -*- coding: UTF-8 -*-
    import traceback
    import json
    import mysql.connector
    # 打开数据库连接
    db = mysql.connector.connect(
           host="localhost",
           user="root",
           passwd="hjf@2019", # 写上你的数据库密码
           database='nba',
           auth_plugin='mysql_native_password'
    )
    # 获取操作游标
    cursor = db.cursor()
    # 执行 SQL 语句
    #cursor.execute("SELECT VERSION()")
    # 获取一条数据
    #data = cursor.fetchone()
    #print("MySQL 版本: %s " % data)
    # 关闭游标 & 数据库连接



    # 插入新球员

    sql = "INSERT INTO player (team_id,player_id,player_name,height) VALUES (%s, %s, %s,%s)"
    val = (1003, 10038," 约翰 - 科林斯 ", 2.08)
    cursor.execute(sql,val)
    db.commit()
    print(cursor.rowcount, " 记录插入成功。")

    cursor.close()
    db.close()
    展开

    作者回复: Good Job

    
    
  • 胡
    2019-08-21
    老师在插入数据的时候,漏掉了 player_id ?

    作者回复: 默认设置的是递增的,就不需要指定player_id

    
    
  • 发条
    2019-07-26
    使用8.0以上版本mysql的同学,在连接数据库的时候可能会受到quth_plugin不支持mysql_native_password的报错,
    可以用ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';语句把auth_plugin改掉

    作者回复: 感谢分享

    
    
  • 大斌
    2019-07-22
    python连接mysql时报错【mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not support】。
    原因是:mysql8.0.11使用了Use Strong Password Encryption for Authentication即强密码加密。
    通常的处理方法是:重装mysql【装更低版本的或者将Use Strong Password Encryption for Authentication改为Use Legacy Authentication Method(在Authentication Method中改)】
    还有一种更好的方案,那就是使用【pymysql】库来连接,代码如下:
        db_host = "localhost"
        db_username = "root"
        db_password = "123456"
        db_name = "database_name"
        conn = pymysql.connect(
            host=db_host,
            user=db_username,
            passwd=db_password,
            database=db_name,
        )
    展开
    
    
  • Geek_5d805b
    2019-07-22
    请问老师关于sql语句中的%s占位问题,如果我要修改多项值可否用变量替代呢?
    
    
  • cricket1981
    2019-07-22
    # -*- coding: UTF-8 -*-

    import mysql.connector
    # 打开数据库连接
    db = mysql.connector.connect(
           host="localhost",
           user="root",
           passwd="root", # 写上你的数据库密码
           database='test',
           auth_plugin='mysql_native_password'
    )
    # 获取操作游标
    cursor = db.cursor()
    sql = 'SELECT * FROM heros WHERE hp_max>=6000'
    cursor.execute(sql)
    data = cursor.fetchall()
    for each_hero in data:
      print(each_hero)
    cursor.close()
    db.close()
    展开

    作者回复: Good Job

    
    
我们在线,来聊聊吧