我觉得造轮子这件事情,是谁都可以做的。只不过做得好或者不好而已,用心了做得就要优雅一点。

之前用过java的代码生成器,什么pojodobodbo都能生成,于是我也来自己造一个轮子。

造轮子的事情是没必要做得,费神费心,还没人家做得好,那么我还是要做,就当是体验一把了,看看细节是怎么实现的。

前期准备:

  1. 一台装有python、mysql的机器和若干待生成的表。
  2. python版本:3.6.4
  3. python安装mysql模块:pip install pymysql。(python2安装:pip install mysql-python
  4. 目标语言:java

待生成为了实现各种数据类型,我们定义一个包含多种数据类型的实体表t_model,数据结构如下。

drop table if exists t_model;
create table t_model(
f_id varchar(64) primary key not null, --varchar 主键
f_number int null,
f_datetime datetime,
f_double double
)


  

目标格式:

package com.dyi.po;

import java.util.Date;
/**
* 表t_model模型
* @author WYB
*
*/
public class Model {
private String id;
private int number;
private Date date;
private double dble; public Model() {
super();
}
public Model(String id, int number, Date date, double dble) {
super();
this.id = id;
this.number = number;
this.date = date;
this.dble = dble;
}
/**
*
* @return
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
*
* @return
*/
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
/**
*
* @return
*/
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
/**
*
* @return
*/
public double getDble() {
return dble;
}
public void setDble(double dble) {
this.dble = dble;
} }

  

开始编写脚本

第一步:查询表结构

    sql = """
select
column_name,data_type,character_maximum_length,column_key,column_comment
from information_schema.`COLUMNS`
where TABLE_NAME = "%s"
"""%tableName
cursor.execute(sql)
tableColumnList = cursor.fetchall()

  

第二步:分析列的类型

cursor.execute(sql)
tableColumnList = cursor.fetchall() modelName = tableName
modelName = modelName[modelName.find("_") + 1:]
modelName = modelName[0].upper()+modelName[1:]
fieldInfoList = []
for col in tableColumnList:
colName = col[0]
colType = col[1].lower()
colLen = col[2]
priKey = col[3]
comment = col[4]

  

第三步:拆分字段名,处理细节,生成代码

import pymysql

##连接数据库
db = pymysql.connect("localhost","root","root","stagebo")
cursor = db.cursor() def log(str):
print(str) def getTableList():
log("开始查询所有数据表...")
cursor.execute("show tables")
tableList = cursor.fetchall()
tList = []
for t in tableList:
tList.append(t[0])
return tList def getTableInfo(tableName):
log("开始获取表结构")
sql = """
select
column_name,data_type,character_maximum_length,column_key,column_comment
from information_schema.`COLUMNS`
where TABLE_NAME = "%s"
"""%tableName
cursor.execute(sql)
tableColumnList = cursor.fetchall() modelName = tableName
modelName = modelName[modelName.find("_") + 1:]
modelName = modelName[0].upper()+modelName[1:]
fieldInfoList = []
for col in tableColumnList:
colName = col[0]
colType = col[1].lower()
colLen = col[2]
priKey = col[3]
comment = col[4]
#字段去掉“f_”
colName = colName[colName.find("_")+1:]
#colName = colName[0].upper()+colName[1:]
#判断类型
type = ""
if colType in ["varchar","nvarchar"]:
type = "String"
elif colType == "int":
type = "int"
elif colType in ["double","float"]:
type = "double" pk = False
if priKey == "PRI":
pk = True
fieldInfoList.append([colName,type,pk]) file = open("%s.java"%modelName, "w")
code = """
package com.dyi.po; import java.util.*; /**
* 表%s模型
*
*/ """ %tableName code += "public class %s {"%modelName
for item in fieldInfoList:
code += """ private %s %s; """%(item[1],item[0]) code +=""" /*
* 空构造函数
*/
public %s(){
super();
} """%modelName code += """
/**
*全参数构造函数
*/
public %s("""%modelName
for item in fieldInfoList:
code += "%s %s, "%(item[1],item[0])
code = code[:-1]
code += """) {
super();"""
for item in fieldInfoList:
code += """
this.%s = %s;"""%(item[0],item[0]) code += """
}""" for item in fieldInfoList:
t = item[1]
n = item[0]
nu = n[0].upper()+n[1:]
code += """ /**
*
* @return
*/
public %s get%s(){
return this.%s;
}
public void set%s(%s %s){
this.%s = %s;
}
"""%(t,nu,n,nu,t,n,n,n)
code += "}"
file.write(code)
file.flush()
file.close() if __name__ == "__main__":
#查询表
tableList = getTableList() #定义要导出的表
tableToScript = ["t_model"] #开始遍历
for tableName in tableToScript:
if tableName not in tableList:
continue
print(tableName)
getTableInfo(tableName)

  结果展示

    package com.dyi.po;

    import java.util.*;

    /**
* 表t_model模型
*
*/ public class Model { private String id; private int number; private date; private double dble; /*
* 空构造函数
*/
public Model(){
super();
} /**
*全参数构造函数
*/
public Model(String id, int number, date, double dble,) {
super();
this.id = id;
this.number = number;
this.date = date;
this.dble = dble;
} /**
*
* @return
*/
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
} /**
*
* @return
*/
public int getNumber(){
return this.number;
}
public void setNumber(int number){
this.number = number;
} /**
*
* @return
*/
public getDate(){
return this.date;
}
public void setDate( date){
this.date = date;
} /**
*
* @return
*/
public double getDble(){
return this.dble;
}
public void setDble(double dble){
this.dble = dble;
}
}

  然后流程就通了,一通百通,别的就可以照旧了~~~

【工具】代码生成器-python脚本的更多相关文章

  1. WebLogic口令猜解工具【Python脚本】

    WebLogic 默认端口7001 可以通过如下链接访问控制台 http://10.9.1.1:7001/console/login/LoginForm.jsp 写了一个简单的猜解脚本,半成品,做个记 ...

  2. Tomcat口令猜解工具【Python脚本】

    Tomcat 服务器网页部署,登录需用户名/密码,编写了一个简单的Python脚本来测试一些简单的弱口令. 测试环境:Tomcat版本 7.0 登录界面采用basic认证,Base 64加密一下,模拟 ...

  3. 转换python脚本为可执行程序的方式

    背景: 部分工具使用python脚本编写,而目标服务器,没有安装python包,导致使用工具不方便,还需要另外安装python. 目前主要有2个主流软件,可做此类转换,把对应工具脚本转换为exe: p ...

  4. ArcGIS使用Python脚本工具

    在Pyhton写的一些代码,用户交互不方便,用户体验比较差,不方便重用.在ArcGIS中可以将用写的Python代码导入到ToolBox中,这样用起来就比较方便了.这里用按要素裁剪栅格的Python来 ...

  5. Java调用Python脚本工具类

    [本文出自天外归云的博客园] 在网上查了很多方法都不成功,在google上搜到一篇文章,做了一些小修改,能够处理中文输出.提取一个运行python脚本的Java工具类如下: package com.a ...

  6. 通过串口工具下发指令的Python脚本

    前言 最近一段时间在测试物联网相关的App自动化,涉及通过串口工具给硬件设备下发指令. 使用的串口工具:SecureCRT 解决办法 通过引用Python的第三方库:serial,通过编写Python ...

  7. 使用python脚本执行地理处理工具

    桌面ArcGIS包含800多种可在Python脚本中运行的地理处理工具. 通过Python脚本来运行地理处理工具,可以处理复杂的工作和执行批处理任务. 案例一:使用脚本执行地理处理工具(以裁剪为例) ...

  8. arcgis python脚本工具实例教程—栅格范围提取至多边形要素类

    arcgis python脚本工具实例教程-栅格范围提取至多边形要素类 商务合作,科技咨询,版权转让:向日葵,135-4855_4328,xiexiaokui#qq.com 功能:提取栅格数据的范围, ...

  9. 使用2种python脚本工具将2个txt文档中的文字进行比较,并计算出Corr, WER正确率,准确率

    一.准备: linux服务器,src2mlf.py   rec2mlf.py   HResults文件,1份源文件和1份需要对比的文件.文件放置于本人云盘 二.使用方法: 1. 对比工具 HResul ...

随机推荐

  1. 如何通过phoenix中查看表的主键信息

    需求描述: 今天一个开发的同事让帮忙查看下表的主键列,在此记录下. 操作过程: 1.通过!primarykeys命令查看表的主键 !primarykeys SYNC_BUSINESS_INFO_BYD ...

  2. 南京IT企业环境之最深心得体会

    我是南京做嵌入式的. 之前搞过一年的PC平台Linux内核开发,Linux内核态的仅仅要不是非常复杂的BUG还是能修复的.一年的Linux用户态软件开发. 然后近期搞了两年ARM嵌入式开发. 做的CM ...

  3. Java课后思考题

    1.简述path和classpath的区别. path:path环境变量是系统环境变量中的一种,它用于保存一系列可执行文件的路径,每个路径之间以分号分隔.当在命令行窗口运行一个可执行文件时,操作系统首 ...

  4. swift开发之--UISearchBar的使用/UISearchController的使用

    记录下UISearchBar的基本用法,补充:ios 8.0以后,原来的UISearchDisplayController被官方废弃,建议使用UISearchController,下面就简单的记录下这 ...

  5. Bitmap之安卓手机壁纸的设置

    MainActivity: package com.hyzhou.imagedemo; import java.io.File; import android.os.Bundle; import an ...

  6. Android 读写位于SD卡上的sqlite数据库文件错误问题

    09-12 15:24:33.903: W/System.err(19499): java.lang.NullPointerException: Attempt to invoke virtual m ...

  7. 【RF库Collections测试】combine lists

    Arguments: [ *lists ]Combines the given `lists` together and returns the result. The given lists are ...

  8. go的临时对象池--sync.Pool

    作者:bigtom链接:https://www.jianshu.com/p/2bd41a8f2254來源:简书   一个sync.Pool对象就是一组临时对象的集合.Pool是协程安全的. Pool用 ...

  9. poj_2286 IDA*

    题目大意 给定一个由数字组成的#字型网格,和一定的移动规则,问最少需要多少次移动才能达到要求的结果. 题目分析 要求最少需要几步到达结果,可以考虑广度优先搜索算法,或者迭代加深深度优先搜索(IDA*) ...

  10. Window PHP 使用命令行模式

    电脑系统: win7 php环境: phpstudy 1 把php目录放到环境变量path下面: 我的电脑->属性->高级->环境变量->系统变量->Path->编 ...