我对 Python 和 MySQL 非常陌生,这是我的第一个 Stack 问题。所以,如果我遗漏了一些明显的东西,请提前道歉。但是,在提问之前我确实尝试过研究一下。
我正在尝试学习 Python、MySQL 和 CGI 脚本编写的基础知识。为此,我一直在阅读教程http://www.tutorialspoint.com/python/python_cgi_programming.htm and http://www.tutorialspoint.com/python/python_database_access.htm等。
我正在尝试让 CURL GET 或 Python Requests GET 调用测试服务器上的 Python CGI 脚本。然后,该 Python CGI 脚本将对本地 MySQL 数据库执行读取操作,并将结果返回到 CURL 或 Python 请求。
我创建的 Python CGI 脚本将 MySQL Read 数据完美输出到远程测试服务器上的终端。但是,它不会将该输出返回到 CURL 或触发 CGI 脚本的 Python 请求。
这是我拼凑而成的 Python CGI 脚本:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fetch data"
# disconnect from server
db.close()
My guess是我需要以某种方式将数据从 SQL 查询传递回 Python 或通过某种 Return 或 Output 语句传递回请求进程。但是,我尽最大努力研究这一点并没有帮助。有人能指出我正确的方向吗?非常感谢您的帮助!
马克:-)