zoukankan      html  css  js  c++  java
  • 专职DBA-使用Python操作MySQL数据库

    专职DBA-使用Python操作mysql数据库
    
    一般使用pymysql这个模块
    MySQLDB这个模块已经很少有人在使用了
    
    1.安装 pymysql 模块
    pip install pymysql
    
    2.使用pymysql模块操作mysql数据库
    导入pymysql模块
    import pymysql
    
    创建和数据库服务器的连接
    conn = pymysql.connect(
        host="localhost",
        port=3306,
        user="root",
        password="123",
        db="student",
        charset="utf8"
    )
    
    创建游标对象
    cursor = conn.cursor()
    
    写sql语句
    sql = "select id,name,sex,age,class from student ;"
    
    执行sql语句的函数
    count = cursor.execute(sql)
    print("sql语句操作影响的行数是{}行。".format(count))
    
    获取结果 获取本次操作的所有数据
    # print(cursor.fetchone())  # 获取一行,返回值类型是元组,表示一条记录
    # ret = cursor.fetchone()  # 获取一行
    # ret = cursor.fetchmany(整型)  # 获取多行
    # ret = cursor.fetchall()  # 获取所有行
    for line in cursor.fetchall():
        print("本次操作的数据是:{}".format(str(line)))
    
    关闭资源,先关闭游标,再关闭数据库连接
    cursor.close()
    conn.close()
    
    
    3.执行语句
    执行sql,更新单条数据,并返回受影响行数
    result = cursor.execute("SQL语句")
    
    插入多条,并返回受影响的函数,例如批量添加
    result2 = cursor.executemany("多条数据")
    sql = """
    insert into student(name,sex,class,age,description) 
    values(%s,%s,%s,%s,%s)
    """
    ret = cursor.executemany(sql,[('张三',1,406,17,'恭喜发财'),('李四',1,406,17,'恭喜发财')])
    
    获取最新自增ID
    new_id = cursor.lastrowid
    
    
    4.操作数据
    commit()提交,保存插入或修改的数据,如果是查询则不需要
    conn.commit()  # 写在execute()之后
  • 相关阅读:
    洛谷 P1550 [USACO08OCT]Watering Hole G(最小生成树||超级源点)
    洛谷 P2168 [NOI2015]荷马史诗(Huffman树|编码)
    洛谷 P5658 括号树(DFS)
    用堆来求中位数
    c++各种输入输出(文件输入输出,标准输入输出,一些字符串)
    Hello,world!
    【NOIP2013】花匠
    【洛谷习题】最长上升子序列
    【NOIP2014】联合权值
    【NOIP2014】飞扬的小鸟
  • 原文地址:https://www.cnblogs.com/zhouwanchun/p/11104611.html
Copyright © 2011-2022 走看看