Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Contains functions to import a text file into a database (SQLite). 

4""" 

5 

6import os 

7from .database_main import Database 

8 

9 

10def import_flatfile_into_database(filedb, filetext, table=None, header=True, 

11 columns=None, engine='SQLite', host='localhost', add_key=None, 

12 encoding="utf-8", fLOG=print): 

13 """ 

14 

15 Function which imports a file into a database. 

16 It the table exists, it removes it first. There is no addition. 

17 

18 @param filedb something.db3 

19 @param filetext something.txt or .tsv 

20 @param table table name (in the database), if None, the database name will be the filename without extension 

21 @param columns if header is False, this must be specified. It should be a list of column names. 

22 @param header boolean (does it have a header or not) 

23 @param engine engine to use when using a SQL server (SQLite or ODBCMSSQL) 

24 @param host host (server) 

25 @param fLOG logging function (will display information through the command line) 

26 @param add_key name of a key to add (or None if nothing to add) 

27 @param encoding encoding 

28 @return table name 

29 

30 .. exref:: 

31 :title: Import a flat file into a SQLite database 

32 :tag: SQL 

33 

34 :: 

35 

36 from pyensae import import_flatfile_into_database 

37 dbf = "database.db3" 

38 file = "textfile.txt" 

39 import_flatfile_into_database(dbf, file) 

40 

41 On Windows, `SQLiteSpy <http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index>`_ is a free tool 

42 very useful to run SQL queries against a sqlite3 database. 

43 """ 

44 # connection 

45 db = Database(filedb, engine=engine, host=host, LOG=fLOG) 

46 db.connect() 

47 

48 if table is None: 

49 table = os.path.splitext( 

50 os.path.split(filetext)[-1])[0].replace(".", "").replace(",", "") 

51 

52 if db.has_table(table): 

53 fLOG("remove ", table) 

54 db.remove_table(table) 

55 

56 if header: 

57 columns = None 

58 

59 db.import_table_from_flat_file(filetext, table, columns=columns, 

60 header=header, add_key=add_key, 

61 encoding=encoding) 

62 

63 db.close() 

64 return table