python 根据 数据库创建java 文件
#coding=utf-8 import pymysql import os import re # 包全路径 packagepath=r'E:\idea工程\dc-exam\dc-exam\src\main\java\org\dcexam\cms\module\entity'.decode('utf-8') # 包名称 packageName="org.dcexam.cms.module.entity" #数据表前缀 prefix='exam_' #数据表名称 ,传入一个list 集合 请注意,如果有重名的表 那么 会 出错误 #就算不再同一个数据库也会出错。。。。请谨慎操作 tableNames=["exam_history"] host="localhost" user="root" password="root" db="exam" for tableName in tableNames: # capitalize 可以将首字母大写 fileName=tableName.replace(prefix,"").capitalize()+".java" print fileName conn = pymysql.connect(host=host,user=user,password=password,database=db,charset="utf8") with conn.cursor() as cursor: cursor.execute('SELECT COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT FROM information_schema.columns WHERE TABLE_NAME="'+tableName+'"') rs = cursor.fetchall() with open(os.path.join(packagepath,fileName),'w+') as file: file.writelines('''package '''+packageName+'''; import lombok.Data; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Data @Table(name = "'''+tableName+'''") public class '''+fileName[:-5]+'''{\n''') for r in rs: col=r[0].encode('utf-8') # 字段名 types=r[1].encode('utf-8') # 类型 javaType='' comment=r[2].encode('utf-8') # 注视 if types.find("tinyint(1)")!=-1: javaType="Boolean " elif types.find("int")!=-1: javaType="Integer " elif types.find("date")!=-1: javaType="String " elif types.find("blob")!=-1: javaType='String ' elif types.find("text")!=-1: javaType='String ' elif types.find("varchar")!=-1: javaType='String ' elif types.find("char")!=-1: javaType='String ' elif types.find("float")!=-1: javaType="Float " elif types.find("double")!=-1: javaType="Double " if(col=='id' or re.compile(r'[a-zA-Z0-9]id').search(col)): line='\t@Id\n\t@GeneratedValue(generator="JDBC")\n\t'+javaType+col+' ; //'+comment+"\n" else: line= ''' '''+javaType+col+' ; //'+comment file.writelines(line+'\n') file.writelines('}')