Return to Snippet

Revision: 16897
at August 18, 2009 16:57 by bingjian


Initial Code
type_str = type('str')
type_datetime = type(datetime.datetime.now())
type_int = type(1)
type_float = type(1.0)
type_None = type(None)


#todo: handle blob data type

def convert2str(record):
    res = []
    for item in record:
        if type(item)==type_None:
            res.append('NULL')
        elif type(item)==type_str:
            res.append('"'+item+'"')
        elif type(item)==type_datetime:
            res.append('"'+str(item)+'"')
        else:  # for numeric values
            res.append(str(item))
    return ','.join(res)



def copy_table(tab_name, src_cursor, dst_cursor):
    sql = 'select * from %s'%tab_name
    src_cursor.execute(sql)
    res = src_cursor.fetchall()
    cnt = 0
    for record in res:
        val_str = convert2str(record)
        try:
            sql = 'insert into %s values(%s)'%(tab_name, val_str)
            dst_cursor.execute(sql)
            cnt += 1
        except:
            print cnt, val_str
    return cnt

Initial URL

                                

Initial Description

                                

Initial Title
Copy a table from one database to another

Initial Tags
database, sql

Initial Language
Python