隨堂練習:新增資料


請試著執行以下程式,觀察 Python 操作資料庫新增資料(因 id 不能重複,所以可以更改新增的 id 或將左方 demo.db 刪除再次執行)。

參考解答

請試著執行以下程式,觀察 Python 操作資料庫新增資料。

# 引入 sqlite3 套件
import sqlite3


# 建立資料庫連線(若無資料庫則新建一個 SQLite 資料庫,本身是一個檔案),以下會建立 demo.db 資料庫
connection = sqlite3.connect('demo.db')

# 使用資料庫 cursor 指標進行 SQL 操作
cursor = connection.cursor()

cursor.execute(
        '''
        CREATE TABLE stocks (
                id INT PRIMARY KEY NOT NULL,
                company_name TEXT NOT NULL,
                price INT NOT NULL
        );
        '''
)

# commit 代表提交,才是真正的將指令在資料庫執行
connection.commit()

# 新增一筆股票資料
cursor.execute(
        '''
        INSERT INTO stocks (id, company_name, price)
        VALUES (2330, '台積電', 220);
        '''
)

connection.commit()

# 最後操作完指令記得關閉資料庫連線
connection.close()


問題討論區
加入問題討論
作業任務區
提交作業任務