📜  Python SQLite——游标对象

📅  最后修改于: 2022-05-13 01:55:20.253000             🧑  作者: Mango

Python SQLite——游标对象

在本文中,我们将讨论Python 的sqlite3模块中的游标对象。

光标对象

它是一个用于建立连接以执行 SQL 查询的对象。它充当 SQLite 数据库连接和 SQL 查询之间的中间件。它是在连接到 SQLite 数据库后创建的。

示例 1:用于创建 hotel_data 数据库并将记录插入到酒店表中的Python代码。

Python3
# importing sqlite3 module
import sqlite3
  
  
# create connection by using object
# to connect with hotel_data database
connection = sqlite3.connect('hotel_data.db')
  
# query to create a table named FOOD1
connection.execute(''' CREATE TABLE hotel
         (FID INT PRIMARY KEY     NOT NULL,
         FNAME           TEXT    NOT NULL,
         COST            INT     NOT NULL,
         WEIGHT        INT);
         ''')
  
# insert query to insert food  details in 
# the above table
connection.execute("INSERT INTO hotel VALUES (1, 'cakes',800,10 )")
connection.execute("INSERT INTO hotel VALUES (2, 'biscuits',100,20 )")
connection.execute("INSERT INTO hotel VALUES (3, 'chocos',1000,30 )")
  
  
print("All data in food table\n")
  
# create a cousor object for select query
cursor = connection.execute("SELECT * from hotel ")
  
# display all data from hotel table
for row in cursor:
    print(row)


Python3
# importing sqlite3 module
import sqlite3
  
# create connection by using object
# to connect with hotel_data database
connection = sqlite3.connect('hotel_data.db')
  
  
# insert query to insert food  details 
# in the above table
connection.execute("INSERT INTO hotel VALUES (1, 'cakes',800,10 )");
connection.execute("INSERT INTO hotel VALUES (2, 'biscuits',100,20 )");
connection.execute("INSERT INTO hotel VALUES (3, 'chocos',1000,30 )");
  
  
print("Food id and Food Name\n")
  
# create a cousor object for select query
cursor = connection.execute("SELECT FID,FNAME from hotel ")
  
# display all data from FOOD1 table
for row in cursor:
     print(row)


输出:

现在转到您的位置并查看 SQLite 数据库已创建。

示例 2:显示酒店表中数据的Python代码。

蟒蛇3

# importing sqlite3 module
import sqlite3
  
# create connection by using object
# to connect with hotel_data database
connection = sqlite3.connect('hotel_data.db')
  
  
# insert query to insert food  details 
# in the above table
connection.execute("INSERT INTO hotel VALUES (1, 'cakes',800,10 )");
connection.execute("INSERT INTO hotel VALUES (2, 'biscuits',100,20 )");
connection.execute("INSERT INTO hotel VALUES (3, 'chocos',1000,30 )");
  
  
print("Food id and Food Name\n")
  
# create a cousor object for select query
cursor = connection.execute("SELECT FID,FNAME from hotel ")
  
# display all data from FOOD1 table
for row in cursor:
     print(row)

输出: