接著上一篇,該篇講述使用python對數據庫進行基本的CRUD操作,這邊以sqlite3為例子,進行說明。sqlite3 是一個非常輕型的數據庫,安裝和使用它是非常簡單的,這邊就不進行講述了。
在python下,已經自帶了sqlite3模塊,供我們使用,這個模塊的用途其實和java當中的jdbc驅動是類似的,通過它,我們就可以非常方便的和sqlite3進行各種操作了。
好了,開始吧。
python的數據庫模塊有統一的接口標準,所有的操作都有統一的模式,大概是分為以下幾步(假設使用的是sqlite3模塊):
具體的相關CRUD實現代碼如下:
import osimport sqlite3#根據傳入的path獲取一個數據庫連接,如果path非法,那么創建一個臨時的內存數據庫def get_conn(path): conn = sqlite3.connect(path) if os.path.exists(path) and os.path.isfile(path): PRint('database path is %s' % format(path)) return conn else: conn = None return sqlite3.connect(':memory')
#獲取游標def get_cursor(conn): if conn is not None: return conn.cursor() else: return get_conn('').cursor()
#創建表數據def create_table(conn, sql): if sql is not None and sql != '': cursor = get_cursor(conn) cursor.execute(sql) conn.commit() close_all(conn, cursor)#關閉數據庫連接def close_all(conn, cursor): try: if cursor is not None: cursor.close() finally: if conn is not None: conn.close()
#CURD操作,需要返回值,查詢是肯定有返回值def crud(conn, sql, data): cursor = get_cursor(conn) n = cursor.execute(sql, data) print("n", n.rowcount) fetchall = cursor.fetchall() conn.commit() close_all(conn, cursor) return fetchall
#CRUD操作,不需要返回值,查詢是肯定有返回值def crud(conn, sql, data): cursor = get_cursor(conn) n = cursor.execute(sql, data) conn.commit() close_all(conn, cursor)
一個簡單的例子:
conn = get_conn('D:/temp/sqlite3/test.db')fetchall = crud(conn, 'select * from student', '')#假設返回的數據有三個字段for row in fetchall: print('name: %s, age: %d, address: %s' % (row[0], row[1], row[2]))
好了,上面的代碼就是最簡單的對python的數據庫操作了。
大家如果有什么問題或者文件有什么錯誤的話,可以留言大家一起探討!
新聞熱點
疑難解答