欢迎访问宙启技术站
智能推送

Python中sql()函数的批量操作和数据批量导入实例

发布时间:2023-12-26 04:33:25

在Python中,sql()函数通常用于执行SQL语句。它可以执行单个SQL语句,也可以执行多个SQL语句的批量操作。

下面是一个使用sql()函数执行单个SQL语句的例子:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('example.db')

# 创建游标对象
cursor = conn.cursor()

# 执行SQL语句
cursor.execute("INSERT INTO students (name, age, grade) VALUES ('John', 18, 'A')")

# 提交事务
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()

上述例子中,我们使用sql()函数执行单个的插入语句将一条学生记录插入到名为students的表中。

如果我们需要执行多个SQL语句的批量操作,可以使用executescript()函数。下面是一个使用executescript()函数执行多个插入语句的例子:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('example.db')

# 创建游标对象
cursor = conn.cursor()

# 执行多个SQL语句的批量操作
cursor.executescript("""
    INSERT INTO students (name, age, grade) VALUES ('John', 18, 'A');
    INSERT INTO students (name, age, grade) VALUES ('Emily', 17, 'B');
    INSERT INTO students (name, age, grade) VALUES ('Michael', 18, 'A');
""")

# 提交事务
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()

上述例子中,我们使用executescript()函数执行了三个插入语句,将三条学生记录同时插入到名为students的表中。

除了使用sql()函数执行SQL语句外,我们还可以使用executemany()函数实现数据的批量导入。下面是一个使用executemany()函数的例子:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('example.db')

# 创建游标对象
cursor = conn.cursor()

# 要导入的数据列表
data = [
    ('John', 18, 'A'),
    ('Emily', 17, 'B'),
    ('Michael', 18, 'A')
]

# 执行批量插入操作
cursor.executemany("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", data)

# 提交事务
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()

上述例子中,我们将三条学生记录存储在一个列表中,并使用executemany()函数一次性将它们导入到名为students的表中。

总结起来,Python中的sql()函数可用于执行单个SQL语句,而executescript()函数可用于执行多个SQL语句的批量操作。此外,executemany()函数可用于实现数据的批量导入。以上是一些使用这些函数的示例。