使用python操作MySQL

    技术2022-07-11  103

    python DB API 规范

    python操作DBMS

    1. 引入API模块 2. 与数据库建立连接; 3. 执行SQL语句 4. 关闭数据库连接

    使用MySQL-connector

    # -*- coding: UTF-8 -*-import mysql.connector# 打开数据库连接db = mysql.connector.connect( host="localhost", user="root", passwd="XXX", # 写上你的数据库密码 database='wucai', auth_plugin='mysql_native_password')# 获取操作游标 cursor = db.cursor()# 执行SQL语句cursor.execute("SELECT VERSION()")# 获取一条数据data = cursor.fetchone()print("MySQL版本: %s " % data)# 关闭游标&数据库连接cursor.close()db.close() 1. Connection * host, user, passwd, port对应Ip, 用户名,密码,端口 * db.close() * db.cursor() * db.begin() * db.commit db.rollback 2. Cursor * cursor.execute(query_sql) * cursor.fetchone() * cursor.fetchall() * cursor.fetchmany(n) * cursor.rowcount * cursor.close()

    对数据表进行增删改查

    import tracebacktry: sql = "INSERT INTO player (team_id, player_name, height) VALUES (%s, %s, %s)" val = (1003, "约翰-科林斯", 2.08) cursor.execute(sql, val) db.commit() print(cursor.rowcount, "记录插入成功。")except Exception as e: # 打印异常信息 traceback.print_exc() # 回滚 db.rollback()finally: # 关闭数据库连接 db.close()
    Processed: 0.017, SQL: 10