您将在下面找到地址db setup on the Colab VM、table creation、data insertion 和data querying 的代码。在单个笔记本单元格中执行所有代码 sn-ps。
但请注意,此示例仅显示如何在非持久 Colab VM 上执行代码。如果您想将数据库保存到 GDrive,您必须先挂载您的 Gdrive (source):
from google.colab import drive
drive.mount('/content/gdrive')
和navigate之后到相应的文件目录。
第 1 步:创建数据库
import sqlite3
conn = sqlite3.connect('SQLite_Python.db') # You can create a new database by changing the name within the quotes
c = conn.cursor() # The database will be saved in the location where your 'py' file is saved
# Create table - CLIENTS
c.execute('''CREATE TABLE SqliteDb_developers
([id] INTEGER PRIMARY KEY, [name] text, [email] text, [joining_date] date, [salary] integer)''')
conn.commit()
测试DB是否创建成功:
!ls
输出:
sample_data SQLite_Python.db
第 2 步:将数据插入数据库
import sqlite3
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
sqlite_insert_query = """INSERT INTO SqliteDb_developers
(id, name, email, joining_date, salary)
VALUES (1,'Python','MakesYou@Fly.com','2020-01-01',1000)"""
count = cursor.execute(sqlite_insert_query)
sqliteConnection.commit()
print("Record inserted successfully into SqliteDb_developers table ", cursor.rowcount)
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("The SQLite connection is closed")
输出:
成功连接到 SQLite
记录成功插入SqliteDb_developers表1
SQLite 连接已关闭
第 3 步:查询数据库
import sqlite3
conn = sqlite3.connect("SQLite_Python.db")
cur = conn.cursor()
cur.execute("SELECT * FROM SqliteDb_developers")
rows = cur.fetchall()
for row in rows:
print(row)
conn.close()
输出:
(1, 'Python', 'MakesYou@Fly.com', '2020-01-01', 1000)