美文网首页
PyMySQL模块

PyMySQL模块

作者: knot98 | 来源:发表于2018-09-17 14:55 被阅读0次
    pymysql模块:
        1. 连接数据库
            conn = pymysql.Connect(
                host="127.0.0.1", # 数据库服务器主机地址 
                user="root",      # 用户名
                password="root",  # 密码
                database="day42", # 数据库名称
                port=3306,      # 端口号
                charset="utf8"    # 编码
            )
        2. 获取游标对象(用于发送和接收数据)
        3. 用游标执行sql语句
        4. 使用fetch方法来获取执行的结果
        5. 关闭链接 先关游标,再关链接
        
        游标的常用方法
        1. 创建游标 conn.cursor(指定查询结果的数据类型)
        2. excute 执行sql
        3. fetchone (当sql只有一条记录时) many(sql有多条并且需要指定条数) all(多条)
        4. scroll 用于修改游标的位置
    

    示例代码如下:

    import pymysql
    
    # 创建链接获取一个链接对象
    conn = pymysql.Connect(
        host="127.0.0.1",
        user="root",
        password="root",
        database="day42",
        port=3306,
        charset="utf8"
    )
    # 获取游标对象  添加参数(pymysql.cursors.DictCursor),返回结果为字典类型
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    # 查询数据
    sql ="select * from test;"
    
    '''
    sql语句:
    select * from test;
    insert into test values(3,'hhh');
    select * from test;
    create table test_2(id int );
    '''
    
    # 执行sql  如果是select 语句返回的是 查询的条数
    res = cursor.execute(sql)
    
    
    print(res)
    
    # 获取查询的结果
    print(cursor.fetchall()) # 打印所有
    # print(cursor.fetchone()) # 逐行打印
    # print(cursor.fetchmany(2)) # 指定打印行数,默认为 1 行
    
    # scroll
    # cursor.scroll(1,"absolute")
    # print(cursor.fetchone())
    # cursor.scroll(-1)
    # print(cursor.fetchall())
    
    
    # 关闭链接
    cursor.close()
    conn.close()
    
    

    相关文章

      网友评论

          本文标题:PyMySQL模块

          本文链接:https://www.haomeiwen.com/subject/stilnftx.html