首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用Python语言从MySQL数据库中获取数据

如何用Python语言从MySQL数据库中获取数据
EN

Stack Overflow用户
提问于 2014-08-25 13:51:43
回答 4查看 43.6K关注 0票数 2

我是python新手,在从MySQL DB获取数据时遇到了一个问题,而我在MySQL查询中传递参数时,我认为我的MySQL语法是不正确的。

这里是屏幕上显示的错误,如下所示。

内部服务器错误

服务器遇到内部错误或配置错误,无法完成您的请求。

请通过webmaster@localhost联系服务器管理员,告知他们此错误发生的时间,以及您在此错误之前执行的操作。

有关此错误的详细信息,请参阅服务器错误日志。本地主机端口80处的Apache/2.4.6 (Ubuntu)服务器

下面是我的Select查询代码,因为我想从Url的get参数中获取数据。

代码语言:javascript
复制
#!/usr/bin/python2.7

import cgi
import cgitb 

cgitb.enable()


print "Content-type: text/html\n\n"

print "<h1>Hello Python</h1>"

#!/usr/bin/python

import MySQLdb

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

# Open database connection
db = MySQLdb.connect("localhost","root","123456789","testdrive" )

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

# Prepare SQL query to INSERT a record into the database
sqlstmt = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = %(first_name)s AND LAST_NAME = %(last_name)s"
    
try:
   # Execute the SQL command
 cursor.execute(sqlstmt, {'first_name': first_name, 'last_name': last_name})
   # 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 fecth data"

# disconnect from server
db.close()
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25479710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档