在python脚本中运行时,如何在文件中存储sql查询的输出(甚至是错误/警告)?

时间:2014-11-27 04:55:13

标签: python sql python-2.7

我正在使用Python IDE在Windows上使用python脚本运行SQL查询。

以下是我连接到DB并执行脚本的示例代码:

#!/usr/bin/python

import MySQLdb
import sys
import cProfile
import re
import timeit

# Open database connection
db = MySQLdb.connect("localhost","bala","bala","mydb" )


# prepare a cursor object using cursor() method
cursor = db.cursor()

import time
start_time = time.time()

// This is simple query, I was running different query,
sqlstr = "SELECT * from accounts"

cursor.execute(sqlstr)
db.commit()

print("--- %s micro seconds ---",  time.time() - start_time)
print  cursor.fetchall()

运行此脚本后,它在控制台上提供输出,但我想将它至少存储在文件或字符串变量中。它可能会导致错误或警告,甚至也可以存储在文件/字符串中。

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/python

import MySQLdb
import sys
import cProfile
import re
import timeit

file = open("filename.txt","w")
# Open database connection
db = MySQLdb.connect("localhost","bala","bala","mydb" )


# prepare a cursor object using cursor() method
cursor = db.cursor()

import time
start_time = time.time()

// This is simple query, I was running different query,
sqlstr = "SELECT * from accounts"
try :    
    a = cursor.execute(sqlstr)
    for i in a :
        file.write(i)
    db.commit()
except :
    file.write(a)

print("--- %s micro seconds ---",  time.time() - start_time)
print  cursor.fetchall()
这可能有用! 我打开了一个文件,其中“filename”是您文件的名称,并在文件名为“filename”的文件中逐行打开并在查询中写入输出。对于错误,我使用了try和except方法。