从技术上讲,可以使用客户端JavaScript连接到数据库。然而,正如其他人已经指出的那样,这样做被认为是非常糟糕的做法,原因有几个——其中最重要的是安全。在
当浏览器被要求加载某个页面时,它会继续向服务器请求在该URL上找到的内容。这意味着页面呈现所需的HTML文件、外部JavaScript文件、图像、样式表和其他资源。由于用户可以访问这些文件,特别是您的JavaScript代码,这意味着他可以访问您的数据库凭据。您可以尝试缩小/模糊代码,但这不会使其更安全。在
如果您确实了解所有的后果,并且出于某种原因您仍然想这样做,请看一下this example.
最好的方法是让服务器处理与数据库的交互。根据您选择的语言,您可以使用PHP(其中包括HTTP服务器,如Apache)、Java、Python等来构建应用程序的这一部分。你甚至可以使用JavaScript(参见Node.js)。在
既然您要求的是一个Python代码片段,这里有一个连接到MySQL数据库并创建一个HTTP服务器来监听端口8080上的连接。对于它将接收到的每个GET请求,脚本将查询数据库并以text/html形式返回结果。在#!/usr/bin/python
import MySQLdb
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method
data = cursor.fetchone()
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(data)
return
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="yourpwd", db="pw_exam")
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()