Use Python to import an MDB database file into the PostgreSQL database sample _python

Source: Internet
Author: User
Tags mdb database postgresql psql access database

The MDB format file can export each of the tables contained in the Mdbtools tool to a CSV format file. Because of the PostgreSQL of the Access database and the format of the database, use Python's file processing to modify the resulting CSV file to the correct, recognizable format.

Import Script Description (This script runs on Linux):

1.apt-get install Mdbtools, install Mdbtools tools

2. Copy the MDB file to the Linux virtual machine, modify the MDB file directory ' dir ' in the script

3. Modify server and database configuration

4. Execute script

Copy Code code as follows:

#-*-Encoding:utf-8-*-
Import OS
Import re
Import PSYCOPG2
Import CSV

#mdb文件目录
dir = R '/home/kotaimen/mdb_file/'
Mdb_tbl_dic = {}


Def make_create_sql ():
If Os.path.isfile (dir + ' Create.sql '):
Os.remove (dir + ' create.sql ')


For Mdb_file in Os.walk (dir):
If Len (mdb_file[2]) >0:
For file_p in mdb_file[2]:
If file_p[-3:] = = ' mdb ':
Print File_p
cmd = ' Mdb-schema%s >>/home/kotaimen/mdb_file/create.sql '
cmd = cmd% (dir + file_p)
Print cmd
Os.system (CMD)
cmd = ' mdb-tables-1%s '% (dir + file_p)
val = Os.popen (cmd). Read ()
Mdb_tbl_dic[file_p] = val.split (' \ n ')
Print Mdb_tbl_dic

Def modefy_create_sql ():
Sql_file_name = dir + ' Create.sql '
Sql_file_name_des = sql_file_name + ' _new '
Fobj = open (Sql_file_name, ' R ')
Fobj_des = open (Sql_file_name_des, ' W ')
For Eachline in Fobj:
#判断表名中是否含有空格
If Eachline.find (' TABLE ') >= 0:
If Eachline.find (';') >= 0:
Start_loc = Eachline.find (' TABLE ') + 6
End_loc = Eachline.find (';')
Tbl_name = Eachline[start_loc:end_loc]
Eachline = Eachline.replace (Tbl_name, ' "' + Tbl_name + '")
Else
Start_loc = Eachline.find (' TABLE ') + 6
End_loc = Eachline.find (' \ n ')
Tbl_name = Eachline[start_loc:end_loc]
Eachline = Eachline.replace (Tbl_name, ' "' + Tbl_name + '")

If Eachline.find (' DROP TABLE ') >= 0:
Eachline = eachline.replace (' drop table ', ' drop table IF EXISTS ')
If Eachline.find (' Table ') >= 0:
Eachline = eachline.replace (' table ', ' "table ')
#create statement with no comma on the last line
If Eachline.find (' Text ') >= 0 and Eachline.find (', ') >0:
loc = Eachline.find (' Text ')
Eachline = Eachline[0:loc] + ' text,\n '
Elif eachline.find (' Text ') >= 0 and Eachline.find (', ') < 0:
loc = Eachline.find (' Text ')
Eachline = Eachline[0:loc] + ' Text \ n '
Fobj_des.writelines (Eachline)
Fobj.close ()
Fobj_des.close ()
Os.remove (Sql_file_name)
Os.rename (Sql_file_name_des, Sql_file_name)

Def make_insert_csv ():
For file_p in Mdb_tbl_dic.keys ():
For TBL in mdb_tbl_dic[file_p]:
If Len (TBL) >0:
cmd = ' mdb-export%s%s >%s.csv '% (dir + file_p, ' "' + tbl + '" ', dir + ' "' + tbl + '") # Tbl.replace (', ' _ '). Rep Lace (' & ', ' _ ')
Os.system (CMD)

Def modefy_insert_csv ():
For Sql_file in Os.walk (dir):
If Len (sql_file[2]) >0:
For file_p in sql_file[2]:
If file_p[-3:] = = ' csv ':
Sql_file_name = dir + file_p
Sql_file_name_des = sql_file_name + ' _new '
Fobj = open (Sql_file_name, ' R ')
Fobj_des = open (Sql_file_name_des, ' W ')
For (Num, Val) in Enumerate (fobj):
Eachline = Val
If num = 0:
col_list = Eachline.split (', ')
Stat = ' COPY ' + ' "' + (File_p[0:-4]) + '" ' + ' (' #+ ('%s, ' *len (line) ') [: -1]+ ') ']
For Col in Col_list:
If col = = ' Table ':
col = ' "' + ' Table ' + '" '
If Col.find (' \ n ') >= 0:
Col.replace (' \ n ', ')
Stat = stat + col + ', '
Stat = stat[:-2] + ' + ' from STDIN with CSV; \ n '
Eachline = Stat

Fobj_des.writelines (Eachline)
Fobj.close ()
Fobj_des.close ()
Os.remove (Sql_file_name)
Os.rename (Sql_file_name_des, Sql_file_name)


Def insert_into_database ():

    cmd = ' psql-h 172.26.11.205-d ap_mapmyindia_full_sample-u postgres-f%s 2>>log.txt '% (dir + ' Create.sql ')
    os.system (cmd)

    for Sql_file in Os.walk (dir):
        If Len (sql_file[2) ) >0:
            for File_p in sql_file[2]:
                 Print file_p
                 if file_p[-3:] = = ' csv ':
                     cmd = ' psql-h 172.26.11.205-d ap_mapmyindia_full_sample-u postgres-f%s 2>>log.txt '% (dir + ' "' + file_p + ' "')
                     Os.system (cmd)


if __name__ = = "__main__":
#1. Create script that makes the table contained in the MDB file
Make_create_sql ()
#2. Modify the illegal characters in the Create script
Modefy_create_sql ()
#3. Export the tables in the MDB to a CSV file
Make_insert_csv ()
#4. Modify CSV script first line, change to copy form
Modefy_insert_csv ()

Insert_into_database ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.