batch insert data version 2

By laserdance, 2 Days ago, written in python.
  1. #-*-coding:utf-8-*-
  2. import pymssql
  3. import time
  4.  
  5. def connection():
  6.     '''
  7.    gain a connection use the atrributes,eg.username,password,host,databasename,dns
  8.    pay attention here,localhost,127.0.0.1 donot recognized by pymssql,only . is right
  9.    '''
  10.     try:
  11.         connection = pymssql.connect(host='.', user='sa', password='123456', database='comsky')
  12.         return connection
  13.     except IOError, ex:
  14.         print str(ex)
  15.         return None
  16. def insert(filename):
  17.     sql="""insert into mobiledata(mobile) values(%s)"""
  18.     conn=connection()
  19.     start=time.time()
  20.     cursor=conn.cursor()
  21.     for line in open(filename).readlines():
  22.         cursor.execute(sql,line)
  23.     conn.commit()
  24.     cursor.close()
  25.     conn.close()
  26.     print 'insert %s cost %.3f second(s)' % (filename,(time.time() - start))
  27. def batchInsert(filename):
  28.     '''
  29. according the list, batchInsert the list into database
  30.    @param filename:
  31.    '''
  32.     sql = '''insert into mobiledata(mobile) values(%s)'''
  33.     BATCHNUM=10000
  34.     conn = connection()
  35.     start_time=time.time()
  36.     cursor = conn.cursor()
  37.     mobiles=open(filename).readlines()
  38.     leng=len(mobiles)
  39.     size=0
  40.     if(leng % BATCHNUM == 0):
  41.         size=leng/BATCHNUM
  42.     else:
  43.         size=1+(leng/BATCHNUM)
  44.     for ind in range(size):
  45.         start=ind*BATCHNUM
  46.         endle=ind*BATCHNUM+BATCHNUM
  47.         cursor.executemany(sql , mobiles[start:endle])
  48.     conn.commit()    
  49.     cursor.close()
  50.     conn.close()
  51.     print 'batchInsert %s cost %.3f second(s)' % (filename,(time.time() - start_time))
  52.        
  53. if __name__ == '__main__':
  54. #    filename = 'F:\\data.txt'
  55.     filename = 'F:\\data\\data.txt'
  56.     batchInsert(filename)
  57.     insert(filename)