"Tools" code generator-python Script

Source: Internet
Author: User
Tags python script

I think the thing that makes wheels is that anyone can do it. Just do it well or not, do it with your heart and you'll be elegant.

Before using Java code generator, what pojodobodbo can be generated, so I also come to build a wheel of my own.

The wheel of the thing is not necessary to do, trouble, and no one else to do well, then I would like to do, when it is a experience, see how the details are realized.

Pre-Preparation:

    1. A machine with Python, MySQL, and a number of tables to be generated.
    2. Python version: 3.6.4
    3. Python install MySQL module: Pip install Pymysql. (Python2 Installation: Pip install Mysql-python
    4. Target language: Java

To generate a table : to implement various data types, we define an entity table T_model with multiple data types, with the following data structure.

drop table if exists t_model;create table T_model (f_id varchar) primary key NOT NULL,--varchar primary key F_number int null,f_d Atetime datetime,f_double Double)

  

Target format:

Package com.dyi.po;import java.util.date;/** * Table T_model 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;th is.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;}}

  

Start writing scripts

First step: Querying the table structure

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

  

Step two: Analyze the type of the column

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]

  

Step three: Split the name of the field, process the details, generate the code

Import pymysql# #连接数据库db = Pymysql.connect ("localhost", "root", "root", "Stagebo") cursor = db.cursor () def log (str): Print  (str) def gettablelist (): Log ("Start querying all data Tables ...") Cursor.execute ("Show tables") Tablelist = Cursor.fetchall () tList = [] for T in TableList:tList.append (T[0]) return tlistdef gettableinfo (tableName): Log ("Start getting table structure") sq L = "" "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 () Colle        n = 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 = "Strin G "elif Coltype = =" int ": type =" int "elif coltype in [" Double "," float "]: type =" Dou ble "PK = False if Prikey = =" PRI ": PK = True fieldinfolist.append ([COLNAME,TYPE,PK]) F    ile = Open ("%s.java"%modelname, "w") code = "" "Package com.dyi.po;    Import java.util.*;        /** * Table%s model * */"" "%tablename Code + =" public class%s {"%modelname for item in Fieldinfolist: Code + = "" "Private%s%s;" "% (        ITEM[1],ITEM[0]) code + = ""/* * Empty constructor */Public%s () {super ();    } "" "%modelname Code + =" "/** * Full parameter constructor */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 Tabletos Cript:if tableName not in tablelist:continue print (tableName) gettableinfo (tableName)

Results Display

    Package Com.dyi.po;    Import java.util.*;                     /** * Table T_model Model * */public class Model {private String ID;                     private int number;                     private date;             Private double dble;        /* Empty constructor */public Model () {super (); }/** * Full parameter constructor */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; }        }

Then the process will pass, follow, the other will be as usual.

"Tools" code generator-python Script

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.