簡體   English   中英

將python代碼的輸出定向到msqldb表

[英]Directing the output of a python code to msqldb table

我正在嘗試將大量動態生成的輸出從python引導到mysql表。我已經成功建立了從python到mysqldb的連接,我也使代碼運行順暢。 現在的問題是,如何將輸出定向到dbase表?

例:

連接到dbase:

import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx",
db="world")
cursor = db.cursor()

需要傳輸其輸出的代碼:

val=xrange(1,1000,2)
for x in val:
    print x

我不習慣同時使用python和mysql。 我可以單獨使用它們,但不能單獨使用。

感謝您的建議。

import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx", db="world")
cursor = db.cursor()

for x in xrange(1,1000,2):
    cursor.execute('INSERT INTO table (mynumber) VALUES(' + str(x) + ');')

像這樣嗎 要么?

一個好主意也是使用.executemany()因為它不會使數據庫阻塞太多。

另一個需要考慮的注意事項是, values = xrange(1,1000,2)for x in xrange(1,1000,2):要慢for x in xrange(1,1000,2):因為您不需要等待xrange()傳遞遍歷它們之前的值, for x in xrange()將使您在生成每個給定數字時執行要執行的任何操作。

暫無
暫無

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

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