顯示具有 SQLite 標籤的文章。 顯示所有文章
顯示具有 SQLite 標籤的文章。 顯示所有文章

2020年1月3日 星期五

sqlite(四) 在django中使用ORM指令

#前言
  • db browser或是django的後台,都能對資料表內容做編輯,
  • django網頁裡,是使用ORM(Object Relational Mapping)的指令來操作sqlite資料表
舉例如下,
Create: table_name.objects.create()
Read: table_name.objects.all(),  db.objects.get(), db.objects.filter()
Update: data_obj.update()
Delete: data_obj.delete()
              data_obj.save()

#網站:練習CRUD(點選功能後,請按GO)


#程式
  • 各頁面說明:
index:首頁
page6是查詢
page7是新增,page9是新增後的結果。
page8是修改,page10是修改後的結果。
page5是刪除,page11是刪除後的結果。

models.py的主要內容
from django.db import models
# 資料表結構
class gasSite(models.Model):
    gassiteName = models.CharField(max_length=20)
    gassiteAddress = models.TextField(max_length=100)
    gassiteOwner = models.TextField(max_length=10)
    gassiteTelephone = models.CharField(max_length=20)

urls.py的內容
from django.contrib import admin
from django.urls import path
from myapp.views import index,page1,page5,page6,page7,page8,page9,page10,page11

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',index),
    path('1/',page1),
    path('5/',page5),
    path('6/',page6),
    path('7/',page7),
    path('8/',page8),
    path('9/',page9),
    path('10/',page10),
    path('11/',page11),
]

views.py的內容
from django.shortcuts import render
# 本程式的資料表
from myapp.models import gasSite

#test測試用
def searchOne(request):
    theResult=gasSite.objects.get(id=3)
    print(theResult)
    return render(request,"list1.html",locals())
#test測試用
def showdata(request):
    dbData=gasSite.objects.all()
    return render(request,"index.html",locals())

#HOME PAGE
def index(request):
    return render(request,"index.html")

#no use後來沒用上了
def page1(request):
    pass
    return render(request,"page1.html",locals())
   
#展示delete的頁面
def page5(request):
    dbData=gasSite.objects.all()
    return render(request,"page5.html",locals())

#列出資料表所有內容
def page6(request):
    dbData=gasSite.objects.all()
    return render(request,"page6.html",locals())

#展示新增資料的頁面
def page7(request):
    pass
    return render(request,"page7.html",locals())
   
#展示修改資料的頁面
def page8(request):
    dbData=gasSite.objects.all()
    return render(request,"page8.html",locals())
   
#展示新增資料完成的結果
def page9(request):
    if request.method=="POST":
        gname=request.POST['gname']
        gaddress=request.POST['gaddress']
        gowner=request.POST['gowner']
        gtelephone=request.POST['gtelephone']
    data1=gasSite.objects.create(gassiteName=gname,gassiteAddress=gaddress,gassiteOwner=gowner,gassiteTelephone=gtelephone)
    data1.save()
    #取出資料庫的最後一筆,用filter,避免有重複的name
    newdata=gasSite.objects.filter(gassiteName=gname)
    newdata=newdata[len(newdata)-1]
    return render(request,"page9.html",locals())
   
#展示修改資料後的結果
def page10(request):
    if request.method=="POST":
        gid=request.POST['gid']
        gname=request.POST['gname']
        gaddress=request.POST['gaddress']
        gowner=request.POST['gowner']
        gtelephone=request.POST['gtelephone']
    data1=gasSite.objects.filter(id=gid)
    data1.update(gassiteName=gname,gassiteAddress=gaddress,gassiteOwner=gowner,gassiteTelephone=gtelephone)
    return render(request,"page10.html",locals())
   

#展示刪除後的結果
def page11(request):
    if request.method=="POST":
        kid=request.POST['hvalue']
        data1=gasSite.objects.get(id=kid)
        data1.delete()
    return render(request,"page11.html",locals())


 

2020年1月2日 星期四

sqlite(三) 在django中建立

#前言
  • django的內定資料庫是sqlite
  • django處理資料庫的方式
    • 建立或修改資料庫,用migrate
    • 建立資料表,用models.py
    • 操作資料表,用admin.py設定。
  • 程式操作資料庫,使用ORM(Object Relational Mapping),而非SQL語言。
  • 版本python 3.7.4


#操作:djago的建立
  • 建立虛擬環境
python -m venv myenv

  • 安裝django
pip install django

  • 建立django project(sqliteproj) 
django-admin startproject sqliteporj

  • 進入sqliteproj資料夾,建立app(myapp)
python manage.py startapp myapp

註:這裡是根目錄,現在裡面有
專案目錄,sqliteproj
app目錄,myapp
一個檔案manage.py

  • 進入專案目錄sqliteproj
編輯settings.py,將myapp加入
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
#操作:資料庫和資料表的建立
  • 進入myapp資料夾,建立資料表結構。
編輯models.py
  1. #models.py的內容
  2. from django.db import models

  3. # 建立資料表gassite的結構
  4. class gassite(models.Model):
  5.     gassiteName = models.CharField(max_length=20)
  6.     gassiteAddress = models.TextField(max_length=100)
  7.     gassiteOwner = models.TextField(max_length=10)
  8.     gassiteTelephone = models.CharField(max_length=20)
  9. #
  10. #資料是宜蘭加油站
  11. #欄位有,加油站名稱,地址,所有人,電話。
編輯 admin.py, 登錄資料表,供django後台管理。
from django.contrib import admin
from myapp.models import *
admin.site.register(gassite)


  • 回到根目錄
產生出db.sqlite3資料庫
python manage.py migrate

建立資料表實體(目前沒有資料)
python manage.py makemigrations myapp
python manage.py migrate myapp

(下載安裝)dbbrowser觀察,資料表名稱是myapp_gassite(實際名稱)

也可以登入django後台來觀察,資料表名稱是gassite(django環境下使用的名稱)
在根目錄,建立管理帳號
python manage.py createsuperuser
(依提示,填入帳號,密碼,email可以enter跳過。)
啟動server
python manage.py runserver 8000
開瀏覽器,用剛才的帳號登入後台,就可以看到gassite了。
http://127.0.0.1:8000/admin

  • 從網路匯入加油站的json資料
下載createdata.py到根目錄中執行,輸入資料庫名稱(db.sqlite3),資料表名稱(myapp_gassite),完成資料匯入。
python createdata.py

用dbbroser觀察內容,可以立即看到明細。

如果用django後台,只能看到gassite object(61), ...gassite object(1)等61筆資訊。必須個別點進去,才能看到明細。 如果要顯示更多欄位,作法請參考 這裡

2019年12月29日 星期日

sqlite(二) 使用python程式

#前言
  • json資料來自網路,所以執行此程式必須連上網路。

#說明
  • 程式說明就夾在程式碼中
  • sqlite3套件,是使用SQL資料庫查詢語言處理。
    • 這裡只做建立資料庫,插入資料和顯示資料的功能。
  • 執行程式中加一點輸入
    • 輸入資料庫名稱,例如,abc.db
    • 輸入資料表名稱,例如,mytable
  • 加一點輸出
    • 使用prettytable套件,讓輸出排列一下
#程式功能說明
  • 1216create-once.py建立資料庫資料表,插入資料。(執行一次就好,否則相同的資料就一直添進去。)
  • 1216showdata-in-table.py 使用prettytable套件輸出的資料。(有的地方排列扭曲了,查不出原因,不像是空格問題。)
#需要DB Browser for SQLite 來幫忙
  • python程式處理資料很快,但是並沒有一個方便的資料庫管理介面,這裡 列有一些工具。

#程式碼
  1. #參考來源: fatdodo所發表的文章,https://cheng-min-i-taiwan.blogspot.com/2019/12/pythonsqlite-open-data.html
  2. import os
  3. import requests 
  4. import json
  5. import sqlite3 ###在python3它是內建,不必在安裝。

  6. '''
  7. 這個程式取自網路資料,所以欄位是固定的,如35-38行。
  8. 1. db=sqlite3.connect("dbName") 建立資料庫
  9. 2. cursor=db.cursor() 指定cursor來定位資料
  10. 3. ###用cursor.execute()執行sql指令 CREATE, 建立table。注意,最好加 IF NOT EXISTS,才不會因為table已存在而出錯。
  11. 4. 用cursor.executemany(sql, data) 執行sql指令,一次多筆資料放進資料表
  12. 5. db.commit() 寫入資料庫
  13. '''


  14. os.system("cls")

  15. #建立資料庫
  16. print("=====建立資料庫=====\n\n")
  17. dbName = input("輸入資料庫名稱,例如abc.db-->    ")
  18. db = sqlite3.connect(dbName)
  19. cursor  = db.cursor() 
  20. print("{}資料庫已經成功建立\n".format(dbName)) 

  21. tableName=input("輸入資料表名稱-->  ")

  22. #準備資料
  23. url  = 'http://www.ilepb.gov.tw/api/ILEPB01001/format/JSON'
  24. print("讀取來自「{}」的資料".format(url))
  25. resp = requests.get(url)
  26. json_dict = json.loads(resp.text)
  27. data = list()
  28. for i in range(len(json_dict)):
  29.     t = (json_dict[i]['加油站名稱'], 
  30.          json_dict[i]['加油站地址'], 
  31.          json_dict[i]['負責人'], 
  32.          json_dict[i]['聯絡電話'])
  33.     data.append(t)

  34. #建資料表,使用sql查詢語言。
  35. sql = '''CREATE TABLE IF NOT EXISTS {:s}(
  36.          ID INTEGER PRIMARY KEY AUTOINCREMENT,
  37.          GAS TEXT NOT NULL, 
  38.          ADDR TEXT NOT NULL, 
  39.          OWNER  TEXT NOT NULL,
  40.          TEL TEXT);'''.format(tableName)
  41. try:
  42.     cursor.execute(sql)
  43. except Exception as e:
  44.     print(e)
  45. #將資料寫入資料表
  46. #多筆資料一次放入,data是先前的tuple
  47. sql = 'INSERT INTO {:s} (GAS, ADDR, OWNER, TEL) VALUES (?,?,?,?);'.format(tableName)
  48. try:
  49.     cursor.executemany(sql, data) #寫入多筆資料的命令
  50.     db.commit() #這個指令才是真正寫入資料庫
  51. except Exception as e:
  52.     print(e)  
  53. print(".......")
  54. print("{}資料表已經完成輸入資料".format(dbName))
  55. cursor.close()

  1. #參考來源: fatdodo所發表的文章,https://cheng-min-i-taiwan.blogspot.com/2019/12/pythonsqlite-open-data.html
  2. import os
  3. import sqlite3 ###在python3它是內建,不必在安裝。

  4. '''
  5. 1. db=sqlite3.connect("dbName") 建立資料庫
  6. 2. cursor=db.cursor() 指定cursor來定位資料
  7. 3. ###用cursor.execute()執行sql指令 CREATE, 建立table。注意,最好加 IF NOT EXISTS,才不會因為table以存在而出錯。
  8. 4. 用cursor.executemany(sql, data) 執行sql指令,一次多筆資料放進資料表
  9. 5. db.commit() 寫入資料庫
  10. '''

  11. def show_table(cursor,tbName):
  12.     sql = 'SELECT * FROM {:s} ORDER BY id ASC;'.format(tbName)
  13.     try:
  14.         cursor.execute(sql)
  15.         rows= cursor.fetchall()
  16.         for i, row in enumerate(rows,1): #1代表i從1開始,內定是從0開始。
  17.             print(i, '>', row)
  18.     except Exception as e:
  19.         print(e)

  20. os.system("cls")
  21.         
  22. #開啟資料庫
  23. print("=====觀看資料表內容=====\n\n")
  24. dbName = input("輸入資料庫名稱,例如abc.db-->  ")
  25. db = sqlite3.connect(dbName)
  26. cursor  = db.cursor() 
  27. print("{}資料庫已經成功開啟\n".format(dbName)) 

  28. tableName = input("輸入要觀看的資料表-->  ")

  29.     
  30. show_table(cursor,tableName)
  31. cursor.close()

  1. #參考來源: fatdodo所發表的文章,https://cheng-min-i-taiwan.blogspot.com/2019/12/pythonsqlite-open-data.html
  2. import os
  3. import sqlite3 ###在python3它是內建,不必在安裝。
  4. from prettytable import PrettyTable

  5. '''
  6. 1. db=sqlite3.connect("dbName") 建立資料庫
  7. 2. cursor=db.cursor() 指定cursor來定位資料
  8. 3. ###用cursor.execute()執行sql指令 CREATE, 建立table。注意,最好加 IF NOT EXISTS,才不會因為table以存在而出錯。
  9. 4. 用cursor.executemany(sql, data) 執行sql指令,一次多筆資料放進資料表
  10. 5. db.commit() 寫入資料庫
  11. '''

  12. def show_table(cursor,tbName):
  13. #建立表格項目名稱
  14.     table = PrettyTable(['編號','加油站名稱','加油站地址','負責人','聯絡電話'])
  15.     table.align = "l" 
  16.     table.border=False
  17.     table.padding_width=3
  18.     
  19.     sql = 'SELECT * FROM {:s} ORDER BY id ASC;'.format(tbName)
  20.     try:
  21.         cursor.execute(sql)
  22.         rows= cursor.fetchall()
  23.         for row in rows: 
  24.             table.add_row(row)
  25.         #印出table
  26.         print(table)
  27.     except Exception as e:
  28.         print(e)

  29. os.system("cls")
  30.         
  31. #開啟資料庫
  32. print("=====觀看資料表內容=====\n\n")
  33. dbName = input("輸入資料庫名稱,例如abc.db-->  ")
  34. db = sqlite3.connect(dbName)
  35. cursor  = db.cursor() 
  36. print("{}資料庫已經成功開啟\n".format(dbName)) 

  37. tableName = input("輸入要觀看的資料表-->  ")





  38.     
  39. show_table(cursor,tableName)
  40. cursor.close()


2019年12月28日 星期六

DB Browser for SQLite

#簡介
DB Browser for SQLite是開源軟體,可以
  • 建立新資料庫
  • 觀看sqlite資料庫內容
  • 設計資料表
  • 編輯資料庫資料
  • 各式匯入匯出


#簡單說明如下,操作很簡單。
(直接在圖內說明)
#編輯資料表結構

sqlite(一) 看sqlite多厲害

#官網資料
  • 使用有多廣泛,下面的系統或裝置中都有sqlite,包山包海啊!
  • Every Android device
  • Every iPhone and iOS device
  • Every Mac
  • Every Windows10 machine
  • Every Firefox, Chrome, and Safari web browser
  • Every instance of Skype
  • Every instance of iTunes
  • Every Dropbox client
  • Every TurboTax and QuickBooks
  • PHP and Python
  • Most television sets and set-top cable boxes
  • Most automotive multimedia systems
  • Countless millions of other applications
  • 特性
  • 任何用途,完全免費。
  • 程式碼公開
  • 開發團隊承諾至少維護到2050年(開始於2000-05-09)
  • 三位全時開發人員

2019年12月13日 星期五

[Python]輕量級資料庫SQLite之介紹 : 擷取政府網站上的Open Data實作為例

目標:

  • 擷取政府網頁上提供的開放資料(Open Data),並將資料儲存至SQLite資料庫中。

輕量級資料庫 SQLite 簡介 (SQLite官網)

  • 免費資料庫。 
  • 支援 C/C++、JAVA、Python 等常見程式語言。 
  • 入門相較於微軟、Oracle資料庫容易。 
  • 主要整合在用戶端程式中,作為本地端儲存資料的常見選擇,像是手機的APP應用程式、嵌入式系統、IOT等所使用。 
  • 具有跨平台優點。 
  • 容易安裝。 
  • 所需的記憶體空間很小(依不同平台,469kbyte~ 11 Mbyte 左右)。 
  • 檔案型資料庫,備份容易。

開放資料 (Open Data)

  • 經過挑選與許可的資料。
  • 這種資料不受著作權、專利權,以及其他管理機制所限制。 
  • 入門相較於微軟、Oracle資料庫容易。 
  • 可以開放給社會公眾,任何人都可以自由出版使用,不論是要拿來出版或是做其他的運用都不加以限制。 
以上對於Open Data的說明來自(WiKi百科)

政府的開放資料 (Open Data) 平臺(官網)


開放資料上常見資料交換格式

  • CSV :逗號分隔值(Comma-Separated Values, CSV)有時也稱為字元分隔值,因為分隔字元也可以不是逗號。 
  • 圖片資料來源(web)

  • XML :可延伸標記式語言(Extensible Markup Language, XML),是一種標記式語言。標記指電腦所能理解的資訊符號,通過此種標記,電腦之間可以處理包含各種資訊的文章等。  
  • 圖片資料來源(web)

  • JSON: 全名為JavaScript Object Notation ,是一種輕量級的資料交換格式,純文字檔且易於閱讀。 

圖片資料來源(web)

程式功能:擷取宜蘭縣加油站資料儲存至 SQLite 資料庫中

  • 擷取加油站的公開資訊。 
  • 儲存到 SQLite資料庫。 

圖片資料來源(web)

程式實作開始


# 作者資訊
__Author__ = 'fatdodo'
# 載入擷取剖析網頁相關套件
import requests 
import json
# 擷取網頁資料
url  = 'http://www.ilepb.gov.tw/api/ILEPB01001/format/JSON'
resp = requests.get(url)
# 資料總長度(字數)
print(len(resp.text))
# 輸出資料 { key : value}
print(resp.text)
# 將JSON文字檔轉譯成符合 Python 字典檔資料
json_dict = json.loads(resp.text)
# 依關鍵字(key)儲存對映的資料(value)
data = list()
for i in range(len(json_dict)):
    t = (json_dict[i]['加油站名稱'], 
         json_dict[i]['加油站地址'], 
         json_dict[i]['負責人'], 
         json_dict[i]['聯絡電話'])
    data.append(t)
# 印出資料(value)內容
for i in data:
    print(i)
# 建立資料庫與連線資料庫
import sqlite3
  • 由於筆者是使用Anaconda內的Jupyter Notebook,本身就有SQLite套件,直接載入SQLite資料庫套件即可。
# 建立資料庫 # dbname : 資料庫名稱。
dbname = 'gas_station.db'
# db : 建立與資料連線,如果資料庫不存在,會自動創建該資料庫。
db = sqlite3.connect(dbname)
# cursor : 可稱為資料指標,要查詢某一筆紀錄必須將cursor指標指到它。
cursor  = db.cursor()                
# 建立資料表 # dbtname : 資料表名稱。
dbtname = 'ilan'
- sql : 用來從資料庫讀取與儲存資料的資料庫特殊語法。
- ID : 資料的索引值。
- GAS : 加油站名稱。
- ADDR : 加油站地址。
- OWNER : 加油站負責人。
- TEL : 加油站電話號碼。
sql = '''CREATE TABLE {:s}(
         ID INTEGER PRIMARY KEY AUTOINCREMENT,
         GAS TEXT NOT NULL, 
         ADDR TEXT NOT NULL, 
         OWNER  TEXT NOT NULL,
         TEL TEXT);'''.format(dbtname)
# 在資料庫內建立資料表
try:
    cursor.execute(sql)
except Exception as e:
    print(e)
# 將加油站資料寫入資料庫中
sql = 'INSERT INTO {:s} (GAS, ADDR, OWNER, TEL) VALUES (?,?,?,?);'.format(dbtname)

try:
    cursor.executemany(sql, data)
    db.commit()
except Exception as e:
    print(e)
# 秀出資料庫資料表ilan內容
def show_recs(myc):
    sql = 'SELECT * FROM {:s} ORDER BY id ASC;'.format(dbtname)
    try:
        myc.execute(sql)
        recs = myc.fetchall()
        print('_____總共有:{:d} 筆____'.format(len(recs)))
        for i, rec in enumerate(recs, 1):
            print(i, '>', rec)
    except Exception as e:
        print(e)
show_recs(cursor)
# 關閉連線資料庫
cursor.close()

2013年4月12日 星期五

[ Android SQLite Project ] 修改資料庫中的資料內容

1.執行程式,按下menu鍵選擇更新功能表。
 
 2. 編輯Boa
 3. 把重量修改成
 4. 查看結果


 5. 修改MainActivity.java程式

 6. 修改EditActivity程式

[ Android SQLite Project ] 新增一筆資料到資料庫

繼續上一篇文章  從資料庫中刪除資料
1. 執行結果,共有6筆資料。

 
2.  選擇手機上的menu鍵,再選擇插入選項。

 
3. 輸入資料(注意我們先不選擇開啟按鈕,因為圖太大,手機太小,會造成無法選選插入鈕)後,再選擇插入鈕。

 5. 可以看出資料已新增
 6. 接下來,介紹設計步驟,首先設計人機介面,記得新增activity_edit.xml檔案,並按下圖新增人機介面。


7. 打開MainActivity.java程式

8. 新增EditActivity.java程式
 9. 新增EditActivity到AndroidMenifest.xml

2013年4月8日 星期一

[ Android SQLite Project ] 從資料庫中刪除資料


 
1. 打開src/MainActivity.java,宣告四個常數及一個變數。
 2. 新增加刪除資料庫中一筆資料的功能。
 3. 新增記綠編輯模式
 4. 執行結果



[ Android SQLite Project ] 製作功能表選單

1. 打開res/values/string.xml檔案,新增加"插入"、"刪除"、"查看"、"更新"等四個字串。

 2. 打開res/menu/main.xml,新增加四個功能表。
 3. 打開src/Mainctivity.java,在適當地方按右鍵,選擇source->Override/Implement Methods選項。
 4. 在Mainctivity.java檔案,加入程式。
 5. 執行結果。



2013年4月7日 星期日

[ Android SQLite Project ] 顯示單筆完整的內容(含讀取SQLite資料庫的圖檔)

1. 執行結果(注意位元圖有經過小畫家的處理,才能顯示出來,讀者若知道請告知,敏哥研判可能是圖檔格式)。


 2. 製作字串
 3. 規劃顯示畫面




 4.修改AnimalActivity.java程式

[ Android SQLite Project ] 利用startActivity及Intent來切換畫面

 
1. 利用Activity來切換畫面

 2. 新增AnimalActivity類別。

 3. 打開AnimalActivity.java,按右鍵,新增onCreate()覆寫函式。

4. 新增setContentView()函式。

 5. 打開layout/activity_main.xml為TextView添加ID。
 6. 回到MainActivity.java把文字內容放在Intent上。
 7. 回到AnimalActivity.java把Intent上的內容取出。
 8. 打開AndroidMenifest.xml新增Activity元件。


9. 執行結果