天天看點

python建立檔案資料庫_python 根據 資料庫建立java 檔案

#coding=utf-8

importpymysqlimportosimportre#包全路徑

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 intableNames:#capitalize 可以将首字母大寫

fileName=tableName.replace(prefix,"").capitalize()+".java"

printfileName

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 inrs:

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='\[email protected]\n\[email protected](generator="JDBC")\n\t'+javaType+col+'; //'+comment+"\n"

else:

line= ''' '''+javaType+col+'; //'+comment

file.writelines(line+'\n')

file.writelines('}')