• Python全栈之路-MySQL(五)


    pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

    #!/usr/bin/env python
    # __Author__: "wanyongzhen"
    # Date: 2017/5/18
    
    import pymysql
    
    # 创建连接
    conn = pymysql.connect(host='192.168.56.11',port=3306,user='db01',passwd='db01',db='db01',charset='utf8')
    
    # 创建游标
    cursor = conn.cursor()
    # 游标设置为字典类型
    # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    # 执行SQL,并返回影响行数
    effect_row = cursor.execute("insert into tb01(id,stu_name) VALUES(2,'wanyongzhen');")
    effect_row = cursor.execute("select * from tb01;")
    print(effect_row)
    # row_1 = cursor.fetchone()   # 获取一条数据
    # row_2 = cursor.fetchmany(3) # 获取多条数据
    # row_3 = cursor.fetchall()   # 获取所有数据
    
    # 注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
    # cursor.scroll(1,mode='relative')  # 相对当前位置移动
    # cursor.scroll(2,mode='absolute')  # 相对绝对位置移动
    
    # 字符串拼接SQL,可以运行,但是禁止此类操作,以免发生SQL注入漏洞
    # inp = input('请输入名字:')
    # sql = "insert into tb01(id,stu_name) VALUES(2,'%s');" % inp
    # cursor.execute(sql)
    
    # 参数传递,必须使用参数的形式
    # inp = input('请输入名字:')
    # id = 1
    # cursor.execute("insert into tb01(id,stu_name) VALUES(%s,%s);",(id,inp))
    # 多条数据操作
    l = [
        (2,'a'),
        (3,'b'),
        (4,'c')
    ]
    cursor.executemany("insert into tb01(id,stu_name) VALUES(%s,%s);",l)
    
    # 获取最新自增ID
    # new_id = cursor.lastrowid
    
    # 打印影响行数
    print(effect_row)
    
    # 提交执行确认
    conn.commit()
    
    # 关闭游标
    cursor.close()
    
    # 关闭连接
    conn.close()
    
  • 相关阅读:
    Java中Collection和Collections的区别
    网站
    window.load 和$(document).ready() 、window.load和body onload区别
    『jQuery』.html(),.text()和.val()的使用
    jQuery选择器总结
    ios开发--编码格式
    iOS开发--基于AFNetWorking3.0的图片缓存分析
    iOS开发--沙盒路径与操作文件
    ios开发--第三方整理
    iOS 网络处理注意点
  • 原文地址:https://www.cnblogs.com/wanyuetian/p/7000571.html
Copyright © 2020-2023  润新知