• python 连接 MySQL并操作


    1. python安装pymsql库:pip install pymysql

    2. 相关代码

    import pymysql

    # 建立连接
    conn = pymysql.connect(
    host="localhost",
    port=3306,
    user="root",
    password="xxxxxxx",
    database="db_name",
    charset="utf8", # 是utf8,不要写成utf-8,否则会报错“'NoneType' object has no attribute 'encoding'”
    cursorclass=pymysql.cursors.DictCursor # 这行代码是把查询结果默认为元组的转换成字典。不加的话返回查询结果是元组,即只有value,没有key
    )
    # 创建游标
    cur = conn.cursor()


    # 删除表,如果存在
    drop_sql = "drop table score_table"
    cur.execute(drop_sql)
    # 创建表
    create_sql = "create table score_table ("
    "id int,"
    "uid int,"
    "course varchar(50),"
    "score int)"
    cur.execute(create_sql)
    # 插入数据。以下插入数据代码运行是成功的,但不知道为什么数据库查询不到这条数据
    insert_sql = "insert into score_table values (111,1008,'数学',69)"
    cur.execute(insert_sql)


    """
    # ================== 查询 =====================
    # 需要执行的SQL语句
    sql = "select * from users_table"
    # 返回的是sql的查询结果条数
    count = cur.execute(sql)
    print(count)
    # 获取结果中的第一条数据
    one = cur.fetchone()
    print("查询的第1条数据为: ",one)
    # 获取结果中的前n条数据.fetchone把第一条数据取走了,所以这里的10条指的是2-11
    many = cur.fetchmany(10)
    print("查询结果前10条数据为: ",many)
    # 获取结果中所有数据.前11条被上面两个给取走了,这里的返回是12-后面所有
    # all = cur.fetchall()
    # print("查询结果的所有数据为: ",all)
    """

    # 关闭游标
    cur.close()
    # 关闭连接
    conn.close()

    3. 根据以上代码,可以封装成一个函数

    运行结果截图

  • 相关阅读:
    转载Dockerfile 中 RUN, CMD, ENTRYPOINT 的区别
    在linux上通过ssh使用github
    dns服务
    centos6 free 和 centos 7的free 的差异与对比
    无重复字符的最长子串
    go get命令在go mod目录下与正常目录执行的区别
    安装git
    转载 筛子算法之golang实现求素数解析
    Go语言基础之并发
    go之无缓冲channel(通道)和有缓冲channel(通道)
  • 原文地址:https://www.cnblogs.com/sue2015/p/15182813.html
Copyright © 2020-2023  润新知