JSONP-сервлет, исполняющий SQL-запросы для WEB-страницы

Сервлет исполняет запросы к MySQL.

Выполнен на Jython - реализации языка программирования Python в среде Java.


Загрузить execsql.py


#!/usr/bin/env jython
# -*- coding: utf-8 -*-
#
# http://advanta.homeip.net:8080/execsql.py?select $ from $ limit $;&&level,number,name,content1&&reports1&&4
#
import java
from javax.servlet import http
from java.net import URLDecoder#, URLEncoder
from java.io import DataInputStream
from com.ziclix.python.sql import zxJDBC
 
class execsql (http.HttpServlet):
  def dbQuery(self, out, sql, cbkfn=None):
    driver= "com.mysql.jdbc.Driver"
    server= "localhost"
    db, usr, passwd= "airs", "airs", "airs"
    url= "jdbc:mysql://%s/%s" % (server, db)
    conn= zxJDBC.connect(url, usr, passwd, driver,CHARSET="UTF-8")
    cursor= conn.cursor()
    try:
      cursor.execute(sql)
    except Exception, e:
      print>>out, `e`
      return
    #
    qType= sql.split()[0].upper()
    if cbkfn!=None:
      print>>out, "%s(" % cbkfn
    if qType=='SELECT':
      kk= 0
      print>>out,"["
      for rs in cursor:
        if kk>0: print>>out,",{"
        else: print>>out,"{",
        kk=1; nn= 0
        for cl in range(len(rs)):
          val= rs[cl]
          nam= cursor.description[cl][0]
          typ= cursor.description[cl][1]
          if nn>0: print>>out,",",
          nn= 1
          if val==None:
            print>>out, "'%s':''" % nam
          elif type(val).__name__=='unicode':
            v1= "'%s':'%s'" % (nam, val.replace("'","\\'"))
            print>>out, v1.encode('utf-8')
          else:
            print>>out, "'%s':%r" % (nam, val)
        print>>out, "}"
      print>>out,"]"
    #if
    elif qType in ('UPDATE','INSERT','DELETE'):
      print>>out, [cursor.updatecount,cursor.warnings,db]
    else:
      pass
    if cbkfn!=None:
      print>>out, ")"
    conn.commit()
    cursor.close()
    conn.close()
  #def dbQuery
  def do(self, req, res):
    req.setCharacterEncoding("UTF-8")
    res.setContentType("text/plain; charset=UTF-8")
    out = res.getOutputStream()
    m1= req.getMethod()
    if m1=='GET':
      rawQS= req.getQueryString()
      if rawQS==None:
        return
    elif m1=='POST':
      if req.getContentLength()<1:
        return
      inp= DataInputStream(req.getInputStream())
      rawQS= inp.readLine()
    else:
      print>>out, "invalid method: '%s'" % m1
      return
    qS= URLDecoder.decode(rawQS)
    qry= qS.split('&&') #!!!
    #--
    while qry[-1]=='':
      del qry[-1]
    #JSONP :
    cbk= qry[0].split('()')
    if len(cbk)==2:
      cbkfuncname= cbk[0]
      del qry[0]
    else:
      cbkfuncname= None
    #
    queryString= qry[0].replace("$","%s") % tuple(qry[1:])
    self.dbQuery(out,queryString,cbkfuncname)
  # def do
  def doGet(self, req, res):
    self.do(req,res)
  def doPost(self, req, res):
    self.do(req,res)
#