Last active
October 21, 2019 06:33
-
-
Save liuyix/6019171 to your computer and use it in GitHub Desktop.
python sqlite3 insert demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def get_firmware_urls(self): | |
| conn = self.get_connection() | |
| result_cur = conn.execute(Downloader_SQLite.SELECT_CHINA_COMMAND) | |
| print type(result_cur) | |
| #print result_cur.fetchone() | |
| result_list = result_cur.fetchall() | |
| print type(result_list) | |
| # for row in result_cur.fetchall(): | |
| # print type(row) | |
| # print row | |
| pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| #-*- encoding:utf-8 -*- | |
| import sqlite3 | |
| DBFILE = "demo.db" | |
| gConn = None | |
| def init_connection(): | |
| global gConn | |
| if gConn == None: | |
| gConn = sqlite3.connect(DBFILE) | |
| def get_connection(): | |
| if gConn == None: | |
| init_connection() | |
| return gConn | |
| def close_connection(): | |
| global gConn | |
| if gConn != None: | |
| gConn.close() | |
| gConn = None | |
| def get_cursor(): | |
| if gConn == None: | |
| init_connection() | |
| return conn.cursor() | |
| def create_table(commit=True): | |
| #cur = get_cursor() | |
| get_connection().execute( | |
| '''CREATE TABLE device | |
| (id INTEGER PRIMARY KEY AUTOINCREMENT, name text)''' | |
| ) | |
| def insert_data(data): | |
| # dynamically detect parameter type: tuple/list/string | |
| conn = get_connection() | |
| INSERT_CMD = "INSERT INTO device(name) VALUES (?)" | |
| do_commit = True | |
| if type(data) == list: | |
| conn.executemany(INSERT_CMD, data) | |
| elif type(data) == tuple: | |
| conn.execute(INSERT_CMD, data) | |
| elif type(data) == str: | |
| conn.execute(INSERT_CMD, (data,)) | |
| else: | |
| # unkown type | |
| do_commit = False | |
| pass | |
| if do_commit: | |
| conn.commit() | |
| def test_create_insert(): | |
| insert_data('make') | |
| insert_data(('github', )) | |
| insert_data([('git', ),('svn',),('hg',)]) | |
| cur = get_connection().cursor() | |
| cur.execute('select name from device') | |
| print cur.fetchall() | |
| close_connection() | |
| if __name__ == "__main__": | |
| test_create_insert() | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment