【工具】代碼產生器-python指令碼

來源:互聯網
上載者:User

標籤:item   select   查詢   分析   ati   一個   code   auth   char   

我覺得造輪子這件事情,是誰都可以做的。只不過做得好或者不好而已,用心了做得就要優雅一點。

之前用過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 tListdef 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指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.