如何在Python执行 SQLite 语句?
在本文中,我们将看到如何使用Python执行 SQLite 语句。我们将执行如何在数据库中创建表、插入记录并显示表中存在的数据。
为了在Python执行 SQLite 脚本,我们将使用execute()方法和connect()对象:
connection_object.execute(“sql statement”)
方法:
要执行执行,我们必须遵循以下步骤:
- 导入 sqlite3 模块。该语句将导入 SQLite 模块,import 关键字用于在Python导入模块。
import sqlite3
- 创建到数据库的连接。这将通过连接数据库来创建一个新数据库,这里我们必须指定数据库名称并使用游标对象连接到它。
connection_object = sqlite3.connect('database_name.db')
- 执行查询连接对象。这里我们需要通过指定SQL语句来执行连接对象。
connection_object.execute("sql statement");
- 最后使用 close() 方法终止连接。
connection_object.close();
示例1:创建数据库和表的Python代码,步骤如下:
- 导入 sqlite3 模块
- 通过使用对象创建连接与 College_details 数据库连接
- SQLite 执行查询以创建表
Python3
# importing sqlite3 module
import sqlite3
# create connection by using object to
# connect with college_details database
connection = sqlite3.connect('college.db')
# sqlite execute query to create a table
connection.execute("""create table college(
geek_id,
geek_name,
address
);""")
print("Table created successfully")
# terminate the connection
connection.close()
Python3
# importing sqlite3 module
import sqlite3
# create connection by using object
# to connect with college_details
# database
connection = sqlite3.connect('college.db')
# sqlite execute query to insert a table
connection.execute(
'''insert into college values ( '7058', 'sravan kumar','hyd' )''')
connection.execute(
'''insert into college values ( '7059', 'jyothika','tenali' )''')
connection.execute(
'''insert into college values ( '7072', 'harsha verdhan','nandyal' )''')
connection.execute(
'''insert into college values ( '7099', 'virinchi','Guntur' )''')
# sqlite execute query to display data
# in the college
a = connection.execute("select * from college")
# fetch all records
print(a.fetchall())
# terminate the connection
connection.close()
输出:
创建的数据库:
示例 2:将数据插入并显示到上面创建的表中的Python代码。
蟒蛇3
# importing sqlite3 module
import sqlite3
# create connection by using object
# to connect with college_details
# database
connection = sqlite3.connect('college.db')
# sqlite execute query to insert a table
connection.execute(
'''insert into college values ( '7058', 'sravan kumar','hyd' )''')
connection.execute(
'''insert into college values ( '7059', 'jyothika','tenali' )''')
connection.execute(
'''insert into college values ( '7072', 'harsha verdhan','nandyal' )''')
connection.execute(
'''insert into college values ( '7099', 'virinchi','Guntur' )''')
# sqlite execute query to display data
# in the college
a = connection.execute("select * from college")
# fetch all records
print(a.fetchall())
# terminate the connection
connection.close()
输出: