Python+Django數據庫配置及使用——執行原始SQL


開發環境

OS:Windows Server 2012

Python:2.7.5

Django:1.5.2

通過 settings.py 配置數據庫

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'ENGINE': 'django.db.backends.sqlite3', #添加數據庫引擎;選項['postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'].
        'NAME': 'F:/TestPython/blog/blog/db/data.db', # 數據庫文件的路徑.
        # The following settings are not used with sqlite3:
        # 下面的配置不適用於sqlite3:
        'USER': '',    # 數據庫登陸用戶名
        'PASSWORD': '', # 數據庫登陸密碼
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. # 主機名
        'PORT': '',                      # Set to empty string for default. # 端口號
    }
}

使用數據庫——查詢

首先引入數據庫模塊

from django.db import connection

假設我的data.db數據庫里面又一張名為 Customer 的表;接下來執行查詢:

data = []
cursor = connection.cursor()
cursor.execute('select * from customer')
for row in cursor.fetchall():
    data.append(row[0])

正常情況下這個執行將會成功。row[0] 表示的是取 Customer 表的第一列的值。

使用數據庫——更新

首先引入數據庫模塊

from django.db import connection,transaction

假設同上,接下來執行更新:

cursor = connection.cursor()
cursor.execute("update customer set customername = '%s',tel = '%s' where Id = 1"%(un,tel))
transaction.commit_unless_managed()  #記得提交事務

總結

對數據庫的操作無非 CRUD ,沒有什么好介紹的。其他數據庫的使用類似,若 Python 沒有集成,可能需要再下載對應數據庫的驅動模塊。還有添加刪除沒有寫,其實有了更新剩下這兩個就很easy了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM