如何从mysql数据库中获取Python中的数据

问题描述 投票:1回答:4

我是python的新手,我在从mysql db获取数据时面临问题,而我在mysql查询中传递参数我认为我的mysql语法不正确。

这是屏幕上显示的错误。

内部服务器错误

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

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

服务器错误日志中可能提供了有关此错误的更多信息。 Apache / 2.4.6(Ubuntu)服务器位于localhost端口80

这是我的代码选择查询,我想从Url的get参数中获取数据。

#!/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()
python mysql cgi
4个回答
0
投票

你在这一行有一个错误

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

这不是PHP,这意味着你不能像这样连接字符串和变量。我假设你不想做准备好的陈述。在这种情况下,您应该阅读以下reply

代码的相关部分如下所示:

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

0
投票

首先,您应该尝试将所有内容抽象为可以在CGI之外调用的单个函数,但现在这是另一个练习。无论如何,如果你已经这样做了,你可以更容易地看到你做错了堆栈跟踪,但是,我可以看到你在有用的代码中有一个语法错误

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

Python字符串连接使用+运算符,而不是像PHP一样使用.

其次,这段代码不安全。见http://xkcd.com/327/

为了解决这个问题,cursor.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})
...

0
投票

我认为我们这里不需要fetchall(),这可能是sqlite代码遗留下来的。做一些像:

for row in cursor:
    x = row[0]
    y = row[1]
    ...

0
投票

试试这个代码

import mysql.connector
from mysql.connector import Error
try:
   mySQLconnection = mysql.connector.connect(host='localhost',
                             database='python_database',
                             user='username',
                             password='passw0rd')
   sql_select_Query = "select * from tablename"
   cursor = mySQLconnection .cursor()
   cursor.execute(sql_select_Query)
   records = cursor.fetchall()

   for row in records:
       print("Sr No = ", row[0], )
       print("Name = ", row[1])
       print("Age  = ", row[2])
       print("Gender  = ", row[3], "\n")
   cursor.close()

except Error as e :
    print ("Error connecting MySQL", e)
finally:
    #closing database connection.
    if(mySQLconnection .is_connected()):
        connection.close()
        print("MySQL connection is closed Now"

Ref

© www.soinside.com 2019 - 2024. All rights reserved.