Python操作SQLite簡明教程_python

來源:互聯網
上載者:User

一、SQLite簡介

SQLite是一個包含在C庫中的輕量級資料庫。它並不需要獨立的維護進程,並且允許使用非標準變體(nonstandard variant)的SQL查詢語句來訪問資料庫。一些應用可是使用SQLite儲存內部資料。它也可以在構建應用原型的時候使用,以便於以後轉移到更大型的資料庫,比如PostgreSQL或者Oracle。

sqlite3模組由Gerhard Häring編寫,提供了一個SQL介面,這個介面的設計遵循了由PEP 249描述的DB-API 2.0說明書。

二、建立並開啟資料庫

為了使用這個模組,必須先建立一個串連(Connection)對象來代表資料庫。在以下的例子中,資料將會被儲存在 example.db 檔案中:

複製代碼 代碼如下:
import sqlite3
conn = sqlite3.connect('example.db')

如果指定的資料庫存在,就會直接開啟這個資料庫,否則將建立一再開啟。
也可以提供專用名 :memory: 來在記憶體中建立資料庫。

三、資料庫連接對象

一旦擁有了串連(Connection)對象,就可以建立遊標(Cursor)對象並調用他的execute()方法來執行SQL語句:

複製代碼 代碼如下:
c = conn.cursor()
 
 # Create table
 c.execute('''CREATE TABLE stocks             
     (date text, trans text, symbol text, qty real, price real)''')
 
 # Insert a row of data
 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
 
 # Save (commit) the changes
 conn.commit()
 
 # We can also close the connection if we are done with it.
 # Just be sure any changes have been committed or they will be lost.
 conn.close()
 

儲存後的資料是持久的,並且可以在以後的訪問中可用。

四、增刪改查

1.建(create)表

複製代碼 代碼如下:
c.execute("create table catalog (id integer primary key,pid integer,name varchar(10) UNIQUE,nickname text NULL)")

上面語句建立了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重複的,以及一個nickname預設為NULL。

2.刪除表(DROP),清空表(TRUNCATE)

複製代碼 代碼如下:
c.execute("drop table catalog")

上面語句將catalog表刪除。

另外SQLite中沒有清空表的操作,使用如下方式替代:

複製代碼 代碼如下:
c.execute("delete from catalog")

3.插入(insert)資料,更改(uptate)資料

通常SQL語句中會用到python變數作為值(value)。不建議直接使用python的字串運算來構造查詢語句,因為這樣是不安全的,會使你的程式容易受到SQL注入攻擊。

可以使用DB-API提供的參數代換。在想使用值(value)的地方放置一個'?'作為預留位置,然後提供一個由值(value)組成的元組作為遊標(cursor)中execute()方法的第二個參數。(其他的資料庫模組可能使用別的預留位置,比如 '%s' 或者 ':1')

複製代碼 代碼如下:

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

c.execute("UPDATE catalog SET trans='SELL' WHERE symbol = 'IBM'")

4.查詢(select)資料

正如前面所說,提倡使用元組進行操作。

複製代碼 代碼如下:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

5.刪除(delete)資料

複製代碼 代碼如下:

t=('RHAT')
c.execute("DELETE * FROM stocks WHERE symbol=?", t)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.