zoukankan      html  css  js  c++  java
  • python操作mysql

    python操作MySQL

    #首先要导入模块pymysql
    import pymysql
    
    #然后建立连接通道
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        password = '123',
        database = 'day38',
        charset = 'utf8'  # 编码千万不要加- 如果写成了utf-8会直接报错
    )
    
    #制作一个游标对象
    cursor = conn.cursor(pymysql.cursors.DictCursor)  # 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息
    
    #写入sql语句
    sql = 'select * from teacher'
    
    #执行sql语句
    cursor.execute(sql)  # 执行传入的sql语句
    # print(res)  # res是执行语句返回的数据条数
    
    #获取结果
    print(cursor.fetchone())  # 只获取一条数据
    print(cursor.fetchone())  # 只获取一条数据
    print(cursor.fetchone())  # 只获取一条数据
    # cursor.scroll(2,'absolute')  # 控制光标移动   absolute相对于其实位置 往后移动几位
    cursor.scroll(1,'relative')  # relative相对于当前位置 往后移动几位
    print(cursor.fetchall())  # 获取所有的数据  返回的结果是一个列表

    sql的注入问题

    import pymysql
    
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        password = '123',
        database = 'day38',
        charset = 'utf8',  # 编码千万不要加- 如果写成了utf-8会直接报错
        autocommit = True  # 这个参数配置完成后  增删改操作都不需要在手动加conn.commit了
    )
    cursor = conn.cursor(pymysql.cursors.DictCursor)  # 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息
    """
    # sql = 'insert into user(name,password) values("jerry","666")'  # 插入一条name为jerry,password为666的数据
    # sql = 'update user set name = "jasonhs" where id = 1'   # 将id为1的字段的那么改为jasonhs
    #sql = 'delete from user where id = 6'  # 删除id为6的数据
    #cursor.execute(sql)
    """
    增删改操作 都必须加一句
    conn.commit()操作
    """
    # conn.commit()
    # username = input('username>>>:')
    # password = input('password>>>:')
    # sql = "select * from user where name =%s and password = %s"
    # print(sql)
    # res = cursor.execute(sql,(username,password))  # 能够帮你自动过滤特殊符号 避免sql注入的问题
    # # execute 能够自动识别sql语句中的%s 帮你做替换
    # if res:
    #     print(cursor.fetchall())
    # else:
    #     print('用户名或密码错误')
    """
    sql注入 就是利用注释等具有特殊意义的符号 来完成一些骚操作
    
    后续写sql语句  不要手动拼接关键性的数据
    而是让excute帮你去做拼接
    """
  • 相关阅读:
    Atitit  Uncaught (in promise) SyntaxError Unexpected token < in JSON at position 0
    Atitit  验证 数字验证 非空验证的最佳算法  h5
    Atitit 转移特效attilax总结
    Atitit Loading 动画效果
    Atitit 项目管理 提升开发效率的项目流程方法模型 哑铃型  橄榄型 直板型
    Atitit hibernate3 hinernate4 hibernate5新特性attilax总结
    Atitit js es5 es6新特性 attilax总结
    Atitit mybatis 3 3.2 3.3  3.4 新特性attilax总结
    Atitit spring 3.0 3.1 3.2 4.0 4.3 5.0 新特性
    Atitit jquery  1.4--v1.11  v1.12  v2.0  3.0 的新特性
  • 原文地址:https://www.cnblogs.com/wangnanfei/p/11399901.html
Copyright © 2011-2022 走看看