[Python] SQLBuilder 演示样例代码

用Python写一个SQLBuilder。Java版能够从 http://www.java2s.com/Code/Java/Database-SQL-JDBC/SQLBuilder.htm 看到。

附上代码:

演示样例代码(一):

class SQLDirector:
  @classmethod
  def buildSQL(cls, builder):
    sql = ""
    sql += builder.getCommand()
    sql += builder.getTable()
    sql += builder.getWhat()
    sql += builder.getCriteria()
    return sql

class SQLBuilder:
  def __init__(self): pass
  def __del__(self): pass

  def getCommand(self): pass
  def getTable(self): pass
  def getWhat(self): pass
  def getCriteria(self): pass

class InsertBuilder(SQLBuilder):

  def __init__(self):
    self._table = ""
    self._columnsAndData = dict()
    self._criteria = ""

  def setTable(self, table):
    self._table = table

  def getCommand(self):
    return "INSERT INTO "

  def getTable(self):
    return self._table

  def getWhat(self):
    columns = list()
    values = list()
    what = ""

    for columnName in self._columnsAndData:
      columns.append(columnName)
      values.append(self._columnsAndData[columnName])

    columns_str = string.join( map(lambda x: str(x), columns), "," )
    values_str = string.join( map(lambda x: str(x), values), "," )

    what += " ("
    what += columns_str
    what += ") VALUES ("
    what += values_str
    what += ") "

    return what

  def getCriteria(self):
    return ""

  def addColumnAndData(self, columnName, value):
    if value:
      self._columnsAndData[columnName] = value

def main():
  builder = InsertBuilder()
  builder.setTable("employees")
  builder.addColumnAndData("employee_id", int(221))
  builder.addColumnAndData("first_name", "‘Shane‘")
  builder.addColumnAndData("last_name", "‘Grinnell‘")
  builder.addColumnAndData("email", "‘[email protected]‘")

  sql = SQLDirector.buildSQL(builder)
  print sql

if __name__ == ‘__main__‘:
  main()

更有意思的玩法。

代码演示样例(二):

#!/usr/bin/env python

import string

class SQLDirector:
  def __init__(self, builder):
    self._builder = builder

  def construct(self):
    self._builder.buildSQL()
    return self._builder.getSQL()

class SQLBuilder:
  def __init__(self): self._sql = ‘‘
  def buildSQL(self): return self
  def getSQL(self): return self._sql

class InsertBuilder(SQLBuilder):
  def __init__(self):
    self._columns = list()
    self._values = list()

  def buildSQL(self):
    columns_str = string.join( map(lambda x: "`%s`" % str(x), self._columns), "," )
    values_str  = string.join( map(lambda x: "‘%s‘" % str(x), self._values), "," )

    self._sql  = "INSERT INTO "
    self._sql += self._table
    self._sql += " (%s) VALUES (%s) " % (columns_str, values_str)

    return self

  def table(self, table):
    self._table = table
    return self

  def column(self, columnName, value):
    self._columns.append(columnName)
    self._values.append(value)
    return self

def main():
  insertBuilder = InsertBuilder()
  insertBuilder.table("dt_process")     .column("attr_key","foo").column("attr_val", "bar")

  sqlDirector = SQLDirector(insertBuilder)
  print sqlDirector.construct()

if __name__ == "__main__":
  main()

演示样例代码(三):

#!/usr/bin/env python

import string

def main():
  insertBuilder = InsertBuilder()
  insertBuilder.table("dt_process")     .column("attr_key","foo").column("attr_val", "bar")

  sqlDirector = SQLDirector(insertBuilder)
  print sqlDirector.construct()

  createBuilder = CreateBuilder()
  createBuilder.table("newTable").ifnotexists()     .column("id").col_type("INTEGER").col_autoincrement()     .column("name").col_type("VARCHAR(40)").col_nullable(False).col_default("empty")

  sqlDirector = SQLDirector(createBuilder)
  print sqlDirector.construct()

# -----------------------------------------------------------------------------
# Libraries
# -----------------------------------------------------------------------------

class SQLDirector:
  def __init__(self, builder):
    self._builder = builder

  def construct(self):
    self._builder.buildSQL()
    return self._builder.getSQL()

class SQLBuilder:
  def __init__(self): self._sql = ‘‘
  def buildSQL(self): return self
  def getSQL(self): return self._sql

class CreateBuilder(SQLBuilder):
  def __init__(self):
    self._columns = list()  # item: dict => ‘name‘, ‘nullable‘, ‘default‘
    self._column_context = None
    self._table = ""
    self._ifnotexists = ""
    self._criteria = ""

  def _map_column(self, column):
    sql = ""
    if column.has_key(‘name‘): sql += " `%s`"%column[‘name‘]
    if column.has_key(‘type‘): sql += " %s"%column[‘type‘]
    if column.has_key(‘nullable‘): sql += "%s"%column[‘nullable‘]
    if column.has_key(‘default‘): sql += "%s"%column[‘default‘]
    if column.has_key(‘auto_increment‘): sql += "%s"%column[‘auto_increment‘]
    return sql

  def _reduce_column(self, left, right):
    return left + ", " + right

  def buildSQL(self):
    columns_str = reduce(self._reduce_column, map( self._map_column, self._columns ))

    self._sql  = "CREATE TABLE "
    self._sql += self._ifnotexists
    self._sql += self._table
    self._sql += " (%s)" % columns_str

    return self

  def ifnotexists(self):
    self._ifnotexists = " IF NOT EXISTS "
    return self

  def table(self, table):
    self._table = table
    return self

  def column(self, columnName):
    column = dict()
    column[‘name‘] = columnName
    self._columns.append(column)
    self._column_context = column
    return self

  def col_type(self, type):
    self._column_context[‘type‘] = type
    return self

  def col_nullable(self, nullable=True):
    if nullable:
      self._column_context[‘nullable‘] = ""
    else:
      self._column_context[‘nullable‘] = " NOT NULL"
    return self

  def col_default(self, default):
    self._column_context[‘default‘] = " DEFAULT %s" % default
    return self

  def col_autoincrement(self, autoincrement=True):
    self._column_context[‘auto_increment‘] = " AUTO_INCREMENT"
    return self

  def primary(self, primary=True):
    self._primary_key.append(self._column_context[‘name‘])
    return self

#
# INSERT INTO
#
class InsertBuilder(SQLBuilder):
  def __init__(self):
    self._columns = list()
    self._values = list()
    self._table = ""

  def buildSQL(self):
    columns_str = string.join( map(lambda x: "`%s`" % str(x), self._columns), "," )
    values_str  = string.join( map(lambda x: "‘%s‘" % str(x), self._values), "," )

    self._sql  = "INSERT INTO "
    self._sql += self._table
    self._sql += " (%s) VALUES (%s) " % (columns_str, values_str)

    return self

  def table(self, table):
    self._table = table
    return self

  def column(self, columnName, value):
    self._columns.append(columnName)
    self._values.append(value)
    return self

if __name__ == "__main__":
  main()
时间: 2024-10-10 18:05:35

[Python] SQLBuilder 演示样例代码的相关文章

C编程规范, 演示样例代码。

/*************************************************************** *Copyright (c) 2014,TianYuan *All rights reserved. * *文件名: standard.h *文件标识: 编程规范演示样例代码 * *当前版本号:V1.0 *作者:wuyq *完毕日期:20140709 * *改动记录1: //改动历史记录.包含改动日期.版本号号.改动人及改动内容等 *改动日期 版本号号 改动人 改动内

10分钟理解Android数据库的创建与使用(附具体解释和演示样例代码)

1.Android数据库简单介绍. Android系统的framework层集成了Sqlite3数据库.我们知道Sqlite3是一种轻量级的高效存储的数据库. Sqlite数据库具有以下长处: (1)零配置,无需安装和配置: (2)储存在单一磁盘文件里的一个完整的数据库. (3)数据库文件能够在不同字节顺序的机器间自由共享: (4)支持数据大小至2TB: (5)足够小.全部源码大致3万行C代码.250KB: (6)比眼下流行的大多数数据库的操作要快. (7)开源. 2.Sqlite 基本操作语句

java 线程、线程池基本应用演示样例代码回想

package org.rui.thread; /** * 定义任务 * * @author lenovo * */ public class LiftOff implements Runnable { protected int countDown=10; private static int taskCount=0; private final int id=taskCount++; public LiftOff(){} public LiftOff(int countDown) { thi

java 状态模式 解说演示样例代码

package org.rui.pattern; import junit.framework.*; /** * 为了使同一个方法调用能够产生不同的行为,State 模式在代理(surrogate)的 * 生命周期内切换它所相应的实现(implementation).当你发现,在决定怎样实现任 对象去耦(Object decoupling) * http://blog.csdn.net/lxwde 28 何一个方法之前都必须作非常多測试的情况下,这是一种优化实现代码的方法.比如, * 童话故事青

1000个经常使用的Python库和演示样例代码

以下是programcreek.com通过分析大量开源码,提取出的最经常使用的python库. 1. sys    (4627) 2. os    (4088) 3. re    (3563) 4. time    (3195) 5. datetime    (2214) 6. random    (2135) 7. unittest    (1928) 8. logging    (1909) 9. urllib    (1884) 10. subprocess    (1756) 11. s

Matlab遗传算法优化问题求解的演示样例代码

代码例如以下: function m_main() clear clc Max_gen = 100;% 执行代数 pop_size = 100;%种群大小 chromsome = 10;%染色体的长度 pc = 0.9;%交叉概率 pm = 0.25;%变异概率 gen = 0;%统计代数 %初始化 init = 40*rand(pop_size, chromsome)-20; pop = init; fit = obj_fitness(pop); [max_fit, index_max] =

boost.python编译及演示样例

欢迎转载,转载请注明原文地址:http://blog.csdn.net/majianfei1023/article/details/46781581 linux编译boost的链接:http://blog.csdn.net/majianfei1023/article/details/46761029 昨天编译安装好boost,今天准备使用boost.python写个python调用c++代码的样例,结果踩了非常多坑. 首先贴上代码: 1.student.cpp,一个普通的c++类 #includ

Java连接redis的使用演示样例

Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sorted list. Redisserver眼下最稳定的版本号是2.8.9,能够到官网http://redis.io/download下载.依据机器的类型及位数下载相应的版本号安装就可以,reids支持linux和windows操作系统. Redisclient支持多种语言,包含:c.C++.C#.php.java.python.go等语

最简单的视音频播放演示样例4:Direct3D播放RGB(通过Texture)

===================================================== 最简单的视音频播放演示样例系列文章列表: 最简单的视音频播放演示样例1:总述 最简单的视音频播放演示样例2:GDI播放YUV, RGB 最简单的视音频播放演示样例3:Direct3D播放YUV,RGB(通过Surface) 最简单的视音频播放演示样例4:Direct3D播放RGB(通过Texture) 最简单的视音频播放演示样例5:OpenGL播放RGB/YUV 最简单的视音频播放演示样例