三 Python增加数据

Python向Mysql增加数据_SQL

注意

在python的pymysql模块,如果需要操作DML语句,需要手动提交事务con.commit()

3.1 插入单挑数据

import pymysql

def add_one():
    # 链接数据库
    con = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test', charset='utf8')
    # 获取操作数据的对象 cursor
    cursor = con.cursor()
    # 编写SQL-DML
    sql = "INSERT INTO product VALUES (0,%s,%s,%s,%s);"
    agrs = (('华为6', 2200, 4, '高端6'))
    # 执行SQL
    cursor.executemany(sql, agrs)
    # 提交事务
    con.commit()
    # 关闭Cursor
    cursor.close()
    # 关闭链接
    con.close()
if __name__ == '__main__':
    add_one()

3.2 插入多条数据

import pymysql

def add_many():
    # 链接数据库
    con = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test', charset='utf8')
    # 获取操作数据的对象 cursor
    cursor = con.cursor()
    # 编写SQL-DML
    sql = "INSERT INTO product VALUES (0,%s,%s,%s,%s);"
    agrs = ((('华为6', 2200, 4, '高端6'), ('华为7', 2200, 4, '高端7')))
    # 执行SQL
    cursor.executemany(sql, agrs)
    # 提交事务
    con.commit()
    # 关闭Cursor
    cursor.close()
    # 关闭链接
    con.close()
if __name__ == '__main__':
    add_many()

Python向Mysql增加数据_python_02