如何使用Python在 SQLite 中执行脚本?
在本文中,我们将了解如何使用Python在 SQLite 中执行脚本。这里我们通过Python执行 create table 和 insert 记录到 table 脚本中。在Python, sqlite3模块支持 SQLite 数据库,用于将数据存储在数据库中。
方法
第 1 步:首先我们需要在Python导入 sqlite3 模块。
import sqlite3
第二步:通过创建数据库连接到数据库。我们可以通过简单地创建一个名为 geeks_db.db 的数据库来连接到数据库,或者我们可以简单地使用:memory在我们的内存中创建一个数据库:
Database creation by name
connection_object = sqlite3.connect(“database_name.db”)
Database creation in Memory:
connection_object = sqlite3.connect:memory:)
第三步:建立数据库连接后创建游标对象。
cursor_object = connection_object.cursor()
第 4 步:编写可执行的 SQL 查询。
cursor_object.executescript(“script”)
第五步:执行游标对象
cursor_object(“sql statement”)
第六步:从数据库中获取表里面的数据。
cursor_object.fetchall()
示例 1:
Python3
# import sqlite3 module
import sqlite3
# create con object to connect
# the database geeks_db.db
con = sqlite3.connect("geeks_db.db")
# create the cursor object
cur = con.cursor()
# execute the script by creating the
# table named geeks_demo and insert the data
cur.executescript("""
create table geeks_demo(
geek_id,
geek_name
);
insert into geeks_demo values ( '7058', 'sravan kumar' );
insert into geeks_demo values ( '7059', 'Jyothika' );
insert into geeks_demo values ( '7072', 'Harsha' );
insert into geeks_demo values ( '7075', 'Deepika' );
""")
# display the data in the table by
# executing the cursor object
cur.execute("SELECT * from geeks_demo")
# fetch all the data
print(cur.fetchall())
Python3
# import sqlite3 module
import sqlite3
# create con object to connect
# the database geeks_db.db
con = sqlite3.connect("geeks_db.db")
# create the cursor object
cur = con.cursor()
# execute the script by creating the table
# named geeks1 and insert the data
cur.executescript("""
create table geeks1(
geek_id,
geek_name,
address
);
insert into geeks1 values ( '7058', 'sravan kumar','hyd' );
insert into geeks1 values ( '7059', 'Jyothika' ,'ponnur' );
insert into geeks1 values ( '7072', 'Harsha','chebrolu' );
insert into geeks1 values ( '7075', 'Deepika','tenali' );
""")
# display the data in the table by
# executing the cursor object
cur.execute("SELECT * from geeks1")
# fetch all the data
print(cur.fetchall())
输出:
示例 2:
蟒蛇3
# import sqlite3 module
import sqlite3
# create con object to connect
# the database geeks_db.db
con = sqlite3.connect("geeks_db.db")
# create the cursor object
cur = con.cursor()
# execute the script by creating the table
# named geeks1 and insert the data
cur.executescript("""
create table geeks1(
geek_id,
geek_name,
address
);
insert into geeks1 values ( '7058', 'sravan kumar','hyd' );
insert into geeks1 values ( '7059', 'Jyothika' ,'ponnur' );
insert into geeks1 values ( '7072', 'Harsha','chebrolu' );
insert into geeks1 values ( '7075', 'Deepika','tenali' );
""")
# display the data in the table by
# executing the cursor object
cur.execute("SELECT * from geeks1")
# fetch all the data
print(cur.fetchall())
输出: