python 개발sqlite3_완전 하 다
#python sqlite
#Author : Hongten
#MailTo : [email protected]
#QQ : 648719819
#Blog : http://www.cnblogs.com/hongten
#Create : 2013-08-09
#Version: 1.0
#DB-API 2.0 interface for SQLite databases
import sqlite3
import os
'''SQLite ,
, 。
python , sqlite3 ,
; ,
, 。
, ,
, (commit)
: conn = sqlite3.connect('c:\\test\\test.db')
: conn = sqlite3.connect('"memory:')
:
conn = sqlite3.connect('c:\\test\\hongten.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 cu is not None:
cu.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\\hongten.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()
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.