如何从MySQL数据库中提取Python中的数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (131)

运行结果显示报错,下面是我的SelectQuery代码:

#!/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()
提问于
用户回答回答于

首先,您应该尝试将所有这些抽象转化为可以在CGI之外调用的单个函数,下列代码中包含了语法错误:

sql = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = '".first_name."' AND LAST_NAME = '".last_name."'"

Python字符串连接使用+作为运算符,而不是像PHP中使用.,要解决此问题,请将cuisor.execute方法提供第二个参数来填充指令:

sqlstmt = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = %(first_name)s AND LAST_NAME = %(last_name)s"

try:
    cursor.execute(sqlstmt, {'first_name': first_name, 'last_name': last_name})
...
用户回答回答于

在这行代码中错误:

sql = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = '".first_name."' AND LAST_NAME = '".last_name."'"

这不是PHP,意味着您不能像这样连接字符串和变量,这种情况下应该阅读以下内容再答复,代码的相关部分如下所示:

cursor.execute("SELECT * FROM EMPLOYEE WHERE FIRST_NAME = %s AND LAST_NAME = %s", [first_name, last_name])

扫码关注云+社区

领取腾讯云代金券