Peter Yang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ###### tags: `python`,`SQLite` # SQLite 來自 老師的網站https://hackmd.io/@amostsai [SQLite 資料庫](https://hackmd.io/@wootu/Bk_pYqWIM?type=view) ## 前言 * 軟體屬於公共財(public domain) * SQLite可說是某種「美德軟體」(virtueware) * 作者本人放棄著作權,而給使用SQLite的人以下的「祝福」(blessing): * May you do good and not evil. 願你行善莫行惡 * May you find forgiveness for yourself and forgive others. 願你原諒自己寬恕他人 * May you share freely, never taking more than you give. 願你寬心與人分享,所取不多於你所施予 * 支援大多數的SQL指令(下面會簡單介紹) * 一個檔案就是一個資料庫。不需要安裝資料庫伺服器軟體 * 完整的Unicode支援(因此沒有跨語系的問題)。 * 速度很快 --- ## 安裝GUI工具 - DB Browser for SQLite 1. 連到[db browser for sqlite](http://sqlitebrowser.org) 2. 點 Windows.exe 3. 安裝 --- ## DB Browser for SQLite特色 * 開放原始碼 * 只能連SQLite ## 資料庫概念 資料庫 -> 資料表 -> 資料列 -> 資料欄 --- ## 新增資料庫 1. 點【新建資料庫】 2. 設定資料庫檔案儲存位置、檔名 ## 新增資料表 1. 點【Create Table】 2. 輸入資料表名稱 3. 點【加入欄位】 4. 點【OK】 ## 修改資料表 1. 點【Database Structure】 2. 在要修改的資料表點右鍵 3. 點【Modify Table】 4. 調整欄位上下順序、新增資料欄、刪除資料欄 5. 點【OK】 6. ctrl + s 儲存更動資料!!! ## 刪除資料表 1. 點【Database Structure】 2. 在要修改的資料表點右鍵 3. 點【刪除資料表】 4. ctrl + s 儲存更動資料!!! --- ## 欄位資料類型 * null: 空值 * integer: 整數資料 * text: 文字資料 * blob: 二進位資料 * real: 浮點數資料 * numeric: ## 欄位特性 * 非空: 一定要有資料 * PK: 主索引鍵 * AI: 自動加1 * U: 唯一值,所有紀錄中該欄位資料不可重複 --- ## 新增/修改資料 1. 點【Browse】 2. 下拉要處理的資料表 3. 點【新建紀錄】 4. ctrl + s 儲存更動資料!!! ## 篩選資料 1. 點【Browse】 2. 下拉要處理的資料表 3. 在【過濾格】輸入要篩選的資料 ## 刪除紀錄 1. 點【Browse】 2. 下拉要處理的資料表 3. 用滑鼠框選要刪除的紀錄 4. 點【刪除記錄】 5. ctrl + s 儲存更動資料!!! --- ## 執行SQL指令 1. 點【Execute】 2. 輸入SQL指令 3. 點【執行】 4. 下方就是執行結果 --- ## 匯出資料庫 1. 打開資料庫檔 2. 點【檔案/匯出/Database to SQL file】 2. 點選要匯出的資料表 3. 點【OK】,輸入檔名 ## 匯入資料庫 1. 點【檔案/匯入/Database from SQL file】 2. 選擇要匯入的sql檔 a. Yes: 匯入到新的資料庫 b. No: 匯入到目前資料庫 --- ## 正規化 資料庫為什麼需要正規化 * 降低資料的重複性 * 避免更新異常 ![](https://3.bp.blogspot.com/-EmWFlv-mjgQ/WnrK2EOQa0I/AAAAAAAQXl0/CrloWacCawABfjemMe_mcxnhp9ukD3JAQCHMYCw/s0/phpDstfIN) (註一) ---- ## SQL語法:資料表處理 * **CREATE TABLE 新增資料表** ```sql= CREATE TABLE user ( 'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 'name' TEXT NOT NULL, 'role' INTEGER NOT NULL DEFAULT 1 ); ``` * **ALTER TABLE .. RENAME TO .. 修改資料表名稱** ```sql= ALTER TABLE book RENAME TO books; ``` * **ALTER TABLE .. ADD .. 新增欄位** ```sql= ALTER TABLE book ADD note text; ``` * **刪除欄位** ```sql= CREATE TABLE book2 AS SELECT id, name, price FROM book; DROP TABLE book; ALTER TABLE book2 RENAME TO book; ``` * **DROP TABLE 刪除資料表** ```sql= DROP TABLE book2; ``` ## SQL語法:資料處理 * **SELECT: 選取紀錄** ```sql= select * from book; select name, price from book; ``` * **DISTINCT: 不顯示重複內容** ```sql= select distinct name FROM book; ``` * **WHERE: 資料篩選** * **= 相同** ```sql= select * from book where name = '咖啡'; ``` * **<> 不相同** ```sql= select * from book where name <> '咖啡'; ``` * **\> 大於** ```sql= select * from book where price > 150; ``` * **< 小於** ```sql= select * from book where price < 200; ``` * **\>= 大於等於** ```sql= select * from book where price >= 150; ``` * **<= 小於等於** ```sql= select * from book where price <= 200; ``` * **BETWEEN 介於** ```sql= select * from book where price between 150 and 190; ``` * **LIKE 符合樣式** ```sql= select * from book where name like '%咖%'; ``` * **IN 在...之中** ```sql= select * from book where id in (1, 2); ``` * **And, OR 並且, 或者** ```sql= select * from book where price > 180 and name like '%美%' select * from book where price > 180 or name like '%美%' ``` * **ORDER BY 排序** * ASC 由小到大 * DESC 由大到小 ```sql= select * from book order by price; select * from book order by price desc; select * from user where role_id = 1 order by name desc; ``` * **INSERT 新增資料** ```sql= insert into book (name, price) values ('美食之旅', 230); ``` * **UPDATE 更新資料** ```sql= update book set name = '美食之旅2', price = 250 where id = 4; ``` * **DELETE 刪除資料** ```sql= delete from book where name = '美食之旅2'; ``` * **JOIN 結合一個以上的table的資料** ```sql= SELECT book.id, book.name, book.price, user.name from book inner join user on book.user_id = user.id; SELECT user.id, user.name, user.account, role.name from user inner join role on user.role_id = role.id; ``` ---- ## python ```python= import sqlite3 conn = sqlite3.connect(r'C:\Users\install\Desktop\書籍管理.db') books = conn.execute('select * from book') for book in books: print(book) ``` ```python= import sqlite3 conn = sqlite3.connect(r'C:\Users\student\Desktop\test.db') add_user_sql = "insert into user (name, account, password) values ('{0}', '{1}', '{2}')" check_user_sql = "select * from user where account='{0}' and password='{1}';" # try: # conn.execute(add_user_sql.format('mos', 'mos@kkk.com', 'qqqqqqqq')) # conn.commit() # except Exception as e: # print(e) try: account = input('請輸入帳號: ') password = input('請輸入密碼: ') res = conn.execute(check_user_sql.format(account, password)).fetchone() if(res == None): print('帳號或密碼錯誤,請重新輸入') else: print('歡迎使用本系統') except Exception as e: print(e) ``` ---- 參考資料: [資料庫正規化練習檔](https://drive.google.com/open?id=1lJTm-FLZvJiO26i7zbHE0TAiNX5V3o0U) [資料庫正規化 Database normalization](https://www.mysql.tw/2017/04/database-normalization.html) [為何使用資料庫儲存資料時,需要先執行正規化?](https://www.ithome.com.tw/node/47440) [說明資料庫正規化基本概念](https://support.microsoft.com/zh-tw/help/283878/description-of-the-database-normalization-basics) [資料庫正規化](http://cc.cust.edu.tw/~ccchen/doc/db_04.pdf) [關聯式資料庫系統的規劃](https://www.slideshare.net/SimonHuang4/ss-31199783) 註一:[資料庫正規化設計題目](https://yamol.tw/tfulltext-資料庫正規化設計題目.htm) [SQLite Tutorial](https://www.quackit.com/sqlite/tutorial/) [SQLite學習手冊](https://wizardforcel.gitbooks.io/sqlite-learning-manual/content/1.html) [SQLite 語法](http://tw.gitbook.net/sqlite/sqlite_syntax.html) [Python 速查手冊12.6 資料庫 sqlite3](http://kaiching.org/pydoing/py/python-library-sqlite3.html) [11.13. sqlite3 — DB-API 2.0 interface for SQLite databases](https://docs.python.org/2/library/sqlite3.html) S20200530 YTC

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully