在测试 Python DB-API 使用流程脚本时,访问出现如下错误:

Premature end of script headers 或 End of script output before headers_数据库连接

查看 Apache 日志,错误信息如下:

Premature end of script headers: dblink.py

或者

End of script output before headers: dblink.py

dblink.py 脚本内容如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "数据库用户名", "数据库密码", "数据库", charset='utf8mb4')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Database version : %s " % data

# 关闭数据库连接
db.close()

通过调试发现,应该是没有标记 HTTP 头部信息结束导致,程序修改如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "数据库用户名", "数据库密码", "数据库", charset='utf8mb4')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Content-type:text/html"
print # 空行,告诉服务器结束头部
print "Database version : %s " % data

# 关闭数据库连接
db.close()

其中," Content-type:text/html" 为 HTTP 头部的一部分,它会发送给浏览器并告诉浏览器文件的内容类型,用 print 输出一个空行用于告诉服务器结束头部信息。

访问结果如下:

Premature end of script headers 或 End of script output before headers_python_02