如何在Python中从MySQL数据库获取数据

2 投票
4 回答
47127 浏览
提问于 2025-04-18 18:24

我刚开始学习Python,现在在从MySQL数据库获取数据时遇到了问题。我在MySQL查询中传递参数时,感觉我的语法可能不对。

屏幕上显示的错误信息是这样的:

内部服务器错误

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

请联系服务器管理员,邮箱是webmaster@localhost,告诉他们这个错误发生的时间,以及你在出错前做了什么。

关于这个错误的更多信息可能在服务器的错误日志中。

Apache/2.4.6 (Ubuntu) 服务器在localhost的80端口上运行

这是我用来执行选择查询的代码,我想从URL的获取参数中提取数据。

   #!/usr/bin/python2.7

import cgi;
import cgitb; cgitb.enable();
import time, calendar;

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()

4 个回答

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"

参考链接

0

我觉得这里其实不需要用到 fetchall(),这个可能是从sqlite的代码里遗留下来的。我们可以直接做一些类似下面的事情:

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

你在这一行有个错误

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])
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})
...

撰写回答