• [转]how to inserting multiple rows in one step


    To insert multiple rows in the table use executemany() method of cursor object.

    Syntax:
    cursor_object.executemany(statement, arguments)

    • statement: string containing the query to execute.
    • arguments: a sequence containing values to use within insert statement.

    Let’s take an example.

    from __future__ import print_function
     
    import MySQLdb as my
     
    db = my.connect(host="127.0.0.1",
    user="root",
    passwd="",
    db="world"
    )
     
    cursor = db.cursor()
    name = "Some new city"
     
    country_code = 'SNC'
     
    district = 'Someyork'
     
    population = 10008
     
    data = [
    ('city 1', 'MAC', 'distrct 1', 16822),
    ('city 2', 'PSE', 'distrct 2', 15642),
    ('city 3', 'ZWE', 'distrct 3', 11642),
    ('city 4', 'USA', 'distrct 4', 14612),
    ('city 5', 'USA', 'distrct 5', 17672),
    ]
     
    sql = "insert into city(name, countrycode, district, population) 
    VALUES(%s, %s, %s, %s)"
     
    number_of_rows = cursor.executemany(sql, data)
    db.commit()
     
    db.close()
    
  • 相关阅读:
    设计模式
    包装类
    php 闭包的理解
    is_null empty isset等的判定
    PHP基础一 $this ,static 和 self的区别
    lumen安装踩过得坑
    composer的使用和安装
    使用submine来写c++
    php 和 thinkphp中的常量一览
    路径问题 ./ / ../ 空 的区别
  • 原文地址:https://www.cnblogs.com/everfight/p/execute_manysql.html
Copyright © 2020-2023  润新知