簡體   English   中英

使用 python 在 SQL 服務器中快速插入數據

[英]Fast Data insertion in SQL Server using python

我想將 CSV 文件中的數據插入到托管在 Azure 上的 SQL 服務器數據庫中。 通過將數據讀入 pandas dataframe 並在 python 的 for 循環中使用 insert 語句,我能夠在表中插入數據。 我正在使用pyodbc 這種方法需要很長時間才能插入數據。 我也試過pd.to_sql() 雖然后者比 for 循環方法快,但它仍然很慢。

有沒有更快的方法使用 python/pandas 在 SQL 服務器中插入 CSV 文件?

使用線程,以便每個線程都可以插入數據庫。 這個人提供了一個很好的例子,他有一個很好的例子。 檢查此鏈接

看看這部分代碼,他啟動了指向插入 function 的線程。

def rnd_user(num=1000001, threadid=1):
  query = u"INSERT INTO imdb.employees (fname, lname, hired, job_code, store_id) VALUES ('%(fname)s','%(lname)s','%(hired)s','%(jobcode)s','%(storeid)s');"
  cnx = mysql.connector.connect(**dbconfig)
  cnx.autocommit = True
  cursor = cnx.cursor()

  def rnd_date():
    return time.strftime("%Y-%m-%d", (random.randrange(2000,2016), random.randrange(1,12), random.randrange(1,28), 0, 0, 0, 0, 1, -1))

  for x in range(num):
    if not shutdown_event.is_set():
      fname = genstring(3, 9)
      lname = genstring(4, 12)
      hired = rnd_date()
      jobcode = genstring(3, 3).upper()
      storeid = random.randrange(1, 20)

      cursor.execute(query % {u'fname': fname, u'lname': lname, u'hired': hired, u'jobcode': jobcode, u'storeid': storeid})

      if x % 1000 == 0:
        print "[%2d] Inserted %d rows" % (threadid, x)

  cnx.close()

... (more code) ...

  for x in range(8):
    t = threading.Thread(target=rnd_user, args=(125000,threadId,))
    t.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM