sqlite3 演示

# python sqlite

import sqlite3
import os

"""SQLite數據庫是一款很是小巧的嵌入式開源數據庫軟件,也就是說
沒有獨立的維護進程,全部的維護都來自於程序自己。
python中,使用sqlite3建立數據庫的鏈接,當咱們指定的數據庫文件不存在的時候
鏈接對象會自動建立數據庫文件;若是數據庫文件已經存在,則鏈接對象不會再建立
數據庫文件,而是直接打開該數據庫文件。
鏈接對象能夠是硬盤上面的數據庫文件,也能夠是創建在內存中的,在內存中的數據庫
執行完任何操做後,都不須要提交事務的(commit)
 
    建立在硬盤上面: conn = sqlite3.connect('c:\\test\\test.db')
    建立在內存上面: conn = sqlite3.connect('"memory:')
 
    下面咱們一硬盤上面建立數據庫文件爲例來具體說明:
        conn = sqlite3.connect('c:\\test\\test.db')
        其中conn對象是數據庫連接對象,而對於數據庫連接對象來講,具備如下操做:
 
        commit()            --事務提交
        rollback()          --事務回滾
        close()             --關閉一個數據庫連接
        cursor()            --建立一個遊標
  
        cu = conn.cursor()
        這樣咱們就建立了一個遊標對象:cu
        sqlite3中,全部sql語句的執行都要在遊標對象的參與下完成
        對於遊標對象cu,具備如下具體操做:
  
        execute()           --執行一條sql語句
        executemany()       --執行多條sql語句
        close()             --遊標關閉
        fetchone()          --從結果中取出一條記錄
        fetchmany()         --從結果中取出多條記錄
        fetchall()          --從結果中取出全部記錄
        scroll()            --遊標滾動
"""

# global var
# 數據庫文件絕句路徑
DB_FILE_PATH = ''

# 表名稱
TABLE_NAME = ''

# 是否打印sql
SHOW_SQL = True


def get_conn(path):
    """獲取到數據庫的鏈接對象,參數爲數據庫文件的絕對路徑
    若是傳遞的參數是存在,而且是文件,那麼就返回硬盤上面改
    路徑下的數據庫文件的鏈接對象;不然,返回內存中的數據接
    鏈接對象"""
    conn = sqlite3.connect(path)
    if os.path.exists(path) and os.path.isfile(path):
        print('硬盤上面:[{}]'.format(path))
        return conn
    else:
        conn = None
        print('內存上面:[:memory:]')
        return sqlite3.connect(':memory:')


def get_cursor(conn):
    """該方法是獲取數據庫的遊標對象,參數爲數據庫的鏈接對象
    若是數據庫的鏈接對象不爲None,則返回數據庫鏈接對象所創
    建的遊標對象;不然返回一個遊標對象,該對象是內存中數據
    庫鏈接對象所建立的遊標對象"""
    if conn is not None:
        return conn.cursor()
    else:
        return get_conn('').cursor()


###############################################################
#            建立|刪除表操做     START
###############################################################


def drop_table(conn, table):
    """若是表存在,則刪除表,若是表中存在數據的時候,使用該
    方法的時候要慎用!"""
    if table is not None and table != '':
        sql = 'DROP TABLE IF EXISTS ' + table
        if SHOW_SQL:
            print('執行sql:[{}]'.format(sql))
        cu = get_cursor(conn)
        cu.execute(sql)
        conn.commit()
        print('刪除數據庫表[{}]成功!'.format(table))
        close_all(conn, cu)
    else:
        print('the [{}] is empty or equal None!'.format(sql))


def create_table(conn, sql):
    """建立數據庫表:student"""
    if sql is not None and sql != '':
        cu = get_cursor(conn)
        if SHOW_SQL:
            print('執行sql:[{}]'.format(sql))
        cu.execute(sql)
        conn.commit()
        print('建立數據庫表[student]成功!')
        close_all(conn, cu)
    else:
        print('the [{}] is empty or equal None!'.format(sql))


###############################################################
#            建立|刪除表操做     END
###############################################################


def close_all(conn, cu):
    """關閉數據庫遊標對象和數據庫鏈接對象"""
    try:
        if cu is not None:
            cu.close()
    finally:
        if conn is not None:
            conn.close()


###############################################################
#            數據庫操做CRUD     START
###############################################################


def save(conn, sql, data):
    """插入數據"""
    if sql is not None and sql != '':
        if data is not None:
            cu = get_cursor(conn)
            for d in data:
                if SHOW_SQL:
                    print('執行sql:[{}],參數:[{}]'.format(sql, d))
                cu.execute(sql, d)
                conn.commit()
            close_all(conn, cu)
    else:
        print('the [{}] is empty or equal None!'.format(sql))


def fetchall(conn, sql):
    """查詢全部數據"""
    if sql is not None and sql != '':
        cu = get_cursor(conn)
        if SHOW_SQL:
            print('執行sql:[{}]'.format(sql))
        cu.execute(sql)
        r = cu.fetchall()
        if len(r) > 0:
            for e in range(len(r)):
                print(r[e])
    else:
        print('the [{}] is empty or equal None!'.format(sql))


def fetchone(conn, sql, data):
    """查詢一條數據"""
    if sql is not None and sql != '':
        if data is not None:
            # Do this instead
            d = (data,)
            cu = get_cursor(conn)
            if SHOW_SQL:
                print('執行sql:[{}],參數:[{}]'.format(sql, data))
            cu.execute(sql, d)
            r = cu.fetchall()
            if len(r) > 0:
                for e in range(len(r)):
                    print(r[e])
        else:
            print('the [{}] equal None!'.format(data))
    else:
        print('the [{}] is empty or equal None!'.format(sql))


def update(conn, sql, data):
    """更新數據"""
    if sql is not None and sql != '':
        if data is not None:
            cu = get_cursor(conn)
            for d in data:
                if SHOW_SQL:
                    print('執行sql:[{}],參數:[{}]'.format(sql, d))
                cu.execute(sql, d)
                conn.commit()
            close_all(conn, cu)
    else:
        print('the [{}] is empty or equal None!'.format(sql))


def delete(conn, sql, data):
    """刪除數據"""
    if sql is not None and sql != '':
        if data is not None:
            cu = get_cursor(conn)
            for d in data:
                if SHOW_SQL:
                    print('執行sql:[{}],參數:[{}]'.format(sql, d))
                cu.execute(sql, d)
                conn.commit()
            close_all(conn, cu)
    else:
        print('the [{}] is empty or equal None!'.format(sql))


###############################################################
#            數據庫操做CRUD     END
###############################################################


###############################################################
#            測試操做     START
###############################################################


def drop_table_test():
    """刪除數據庫表測試"""
    print('刪除數據庫表測試...')
    conn = get_conn(DB_FILE_PATH)
    drop_table(conn, TABLE_NAME)


def create_table_test():
    """建立數據庫表測試"""
    print('建立數據庫表測試...')
    create_table_sql = '''CREATE TABLE `student` (
                          `id` int(11) NOT NULL,
                          `name` varchar(20) NOT NULL,
                          `gender` varchar(4) DEFAULT NULL,
                          `age` int(11) DEFAULT NULL,
                          `address` varchar(200) DEFAULT NULL,
                          `phone` varchar(20) DEFAULT NULL,
                           PRIMARY KEY (`id`)
                        )'''
    conn = get_conn(DB_FILE_PATH)
    create_table(conn, create_table_sql)


def save_test():
    """保存數據測試..."""
    print('保存數據測試...')
    save_sql = '''INSERT INTO student values (?, ?, ?, ?, ?, ?)'''
    data = [(1, 'Hongten', '', 20, '廣東省廣州市', '13423****62'),
            (2, 'Tom', '', 22, '美國舊金山', '15423****63'),
            (3, 'Jake', '', 18, '廣東省廣州市', '18823****87'),
            (4, 'Cate', '', 21, '廣東省廣州市', '14323****32')]
    conn = get_conn(DB_FILE_PATH)
    save(conn, save_sql, data)


def fetchall_test():
    """查詢全部數據..."""
    print('查詢全部數據...')
    fetchall_sql = '''SELECT * FROM student'''
    conn = get_conn(DB_FILE_PATH)
    fetchall(conn, fetchall_sql)


def fetchone_test():
    """查詢一條數據..."""
    print('查詢一條數據...')
    fetchone_sql = 'SELECT * FROM student WHERE ID = ? '
    data = 1
    conn = get_conn(DB_FILE_PATH)
    fetchone(conn, fetchone_sql, data)


def update_test():
    """更新數據..."""
    print('更新數據...')
    update_sql = 'UPDATE student SET name = ? WHERE ID = ? '
    data = [('HongtenAA', 1),
            ('HongtenBB', 2),
            ('HongtenCC', 3),
            ('HongtenDD', 4)]
    conn = get_conn(DB_FILE_PATH)
    update(conn, update_sql, data)


def delete_test():
    """刪除數據..."""
    print('刪除數據...')
    delete_sql = 'DELETE FROM student WHERE NAME = ? AND ID = ? '
    data = [('HongtenAA', 1),
            ('HongtenCC', 3)]
    conn = get_conn(DB_FILE_PATH)
    delete(conn, delete_sql, data)

###############################################################
#            測試操做     END
###############################################################


def init():
    """初始化方法"""
    # 數據庫文件絕句路徑
    global DB_FILE_PATH
    DB_FILE_PATH = 'c:\\test\\test.db'
    # 數據庫表名稱
    global TABLE_NAME
    TABLE_NAME = 'student'
    # 是否打印sql
    global SHOW_SQL
    SHOW_SQL = True
    print('show_sql : {}'.format(SHOW_SQL))
    # 若是存在數據庫表,則刪除表
    drop_table_test()
    # 建立數據庫表student
    create_table_test()
    # 向數據庫表中插入數據
    save_test()


def main():
    init()
    fetchall_test()
    print('#' * 50)
    fetchone_test()
    print('#' * 50)
    update_test()
    fetchall_test()
    print('#' * 50)
    delete_test()
    fetchall_test()


if __name__ == '__main__':
    main()
相關文章
相關標籤/搜索