js簡單程式碼生成器

阿杜_ardo發表於2017-12-02

2012年寫的一個js簡單程式碼生成器,通過oracle的建表語句自動生成你想要的java、sql、js程式碼

如圖:


javascript程式碼:

function $(id){
	return document.getElementById(id);
}

var copytoclip=1;
function HighlightAll(theField) {                                      
	var tempval=eval("document."+theField)      
	tempval=document.all[theField];
	tempval.focus()                                      
	tempval.select()                                      
	if (document.all&&copytoclip==1){                                      
	therange=tempval.createTextRange()                                      
	therange.execCommand("Copy")}
} 

function trimString(str, wh){
		if(!str.replace){ return str; }
		if(!str.length){ return str; }
		var re = (wh > 0) ? (/^\s+/) : (wh < 0) ? (/\s+$/) : (/^\s+|\s+$/g);
		return str.replace(re, "");
};


//============================================

var C_DefaultValue={
'int' : '0',
'long' : '0',
'float' : '0',
'double' : '0',
'String' : 'null',

'Integer' : 'null',
'Long' : 'null',
'Float' : 'null',
'Double' : 'null',

'Object' : 'null'
};

var C_Context={
'varName_vo' :'vo',
'varName_rs' :'rs',
'varName_stmt' :'pstmt',
'varName_sqlbd' :'sqlbd',

'':''
};



function field2property(inField){

	var field=inField.toLowerCase();
	var prop=field;
	var cutRule;

	for (var i=1;i<3;i++ ){
		cutRule=arguments[i];
		if (!cutRule || cutRule==''){
			break;
		}
		cutRule=cutRule.toLowerCase();
		if (cutRule.indexOf('_')==0 && field.lastIndexOf(cutRule)==field.length- cutRule.length){
			prop=prop.substring(0,prop.length-cutRule.length);
		}else if (field.indexOf(cutRule)==0){
			prop=prop.substring(cutRule.length);
		}

	}

	prop=prop.toLowerCase();

	var tempProps=prop.split('_');
	for (var i=1;i<tempProps.length ;i++ ){
		tempProps[i]=tempProps[i].substring(0,1).toUpperCase()+tempProps[i].substring(1);
	}

	prop=tempProps.join('');
	return prop;

}



var Field=function(fString){
	var Me=this;
	Me.orgString=fString;
	Me.name;
	Me.type;
	Me.codeName;
	Me.codeType;

	Me.setterName;
	Me.getterName;

	init();
	
	Me.test=function(){
		alert(Me.orgString+"\n"+
				Me.name+"\n"+
				Me.codeName+"\n"+
				Me.codeType+"\n"+
				"");
	};
	function init(){
		var	lineStr=Me.orgString.replace("\t+"," ");
		var fs=Me.orgString.indexOf(" ");
		Me.name=Me.orgString.substring(0,fs);
		Me.codeName=field2property(Me.name,"f_");

		Me.setterName="set"+Me.codeName.substring(0,1).toUpperCase()+Me.codeName.substring(1);
		Me.getterName="get"+Me.codeName.substring(0,1).toUpperCase()+Me.codeName.substring(1);

		var otype=trimString( Me.orgString.substring(fs) );

		if (otype.indexOf("VARCHAR")==0){
			Me.codeType="String";
		}else if (otype.indexOf("TEXT")==0){
			Me.codeType="String";
		}else if (otype.indexOf("DATE")==0){
			Me.codeType="String";
		}else if (otype.indexOf("NUMBER(")==0){
			var tnumlengths=otype.substring(7,otype.indexOf(")") ).split(',');
			var isFloat=tnumlengths.length>1?true:false;
			var isBig= parseInt(tnumlengths[0])>9?true:false;
			if (isFloat && isBig){
				Me.codeType="double";
			}else if(isFloat && !isBig){
				Me.codeType="float";
			}else if(!isFloat && isBig){
				Me.codeType="long";
			}else{
				Me.codeType="int";
			}
		}else if (otype.indexOf("NUMBER")==0){
			Me.codeType="int";
		}else if (otype.indexOf("INT")==0){
			Me.codeType="int";
		}

		Me.type=Me.codeType.substring(0,1).toUpperCase()+Me.codeType.substring(1);
	};


};




var getTableName=function(sqlString){

	sqlString=trimString(sqlString);
	var lineStrs=sqlString.split("\r");
	firstLine=trimString(lineStrs[0]).toUpperCase();
	if (firstLine.indexOf("CREATE ")<0){
		return "<未知的表名稱>";
	}
	var fs=firstLine.indexOf("(");
	if (fs>0){
		firstLine=firstLine.substring(0,fs);
	}

	return firstLine.replace(/(\s+)/g, " ").split(" ")[2];
}

var genFields=function(sqlString){

sqlString=trimString(sqlString);
var rsString='';
var fieldsList=[];
var lineStrs=sqlString.split("\r");

for (i=0;i<lineStrs.length;i++) {

	var lineStr=trimString(lineStrs[i]).toUpperCase();
	if (lineStr.indexOf("CREATE ")==0 || lineStr.indexOf("CONSTRAINT ")==0 || lineStr.indexOf("--")==0){
		continue;
	}
	if (lineStr.lastIndexOf(",")==lineStr.length-1){
		lineStr=lineStr.substring(0,lineStr.length-1);
	}
	if (lineStr.indexOf("(")==0 || lineStr.indexOf(")")==0){
		lineStr=lineStr.substring(1);
	}

	if (lineStr.length>0){
		fieldsList.push( new Field(lineStr) );
	}
}

return fieldsList;

}




var CodeGen={

"VO_Property":function(){
		var fields=genFields($("sql_zone").value);
		var returnStr=[];

		for (var i=0;i<fields.length ;i++ ){
			returnStr.push( 'private '+fields[i].codeType+" "+fields[i].codeName+' = '+C_DefaultValue[fields[i].codeType]+' ;' );
		}
		return returnStr.join("\r\n");

},

"VO_Getter":function(){
		var fields=genFields($("sql_zone").value);
		var returnStr=[];

		for (var i=0;i<fields.length ;i++ ){
			returnStr.push('public '+fields[i].codeType+' '+fields[i].getterName+'() {');
			returnStr.push('\t'+"return "+fields[i].codeName+';');
			returnStr.push( '}\r\n' );
		}
		return returnStr.join("\r\n");

},

"VO_Setter":function(){
		var fields=genFields($("sql_zone").value);
		var returnStr=[];

		for (var i=0;i<fields.length ;i++ ){
			returnStr.push('public void '+fields[i].setterName+'('+ fields[i].codeType +' '+ fields[i].codeName +') {');
			returnStr.push('\t'+"this."+fields[i].codeName+' = '+fields[i].codeName+' ;');
			returnStr.push( '}\r\n' );
		}
		return returnStr.join("\r\n");

},


"SQL_Select":function(){
		var fields=genFields($("sql_zone").value);
		var tableName=getTableName($("sql_zone").value);
		var alName="a";
		
		var fieldsStr=[];
		for (var i=0;i<fields.length ;i++ ){
			fieldsStr.push( alName+"."+fields[i].name );
		}

		return "SELECT \r\n "+fieldsStr.join(',')+" \r\n FROM "+tableName+" "+alName+" WHERE 1=1;"

},

"SQL_Insert":function(){
		var fields=genFields($("sql_zone").value);
		var tableName=getTableName($("sql_zone").value);

		var fieldsStr=[];
		var argsStr=[];
		for (var i=0;i<fields.length ;i++ ){
			fieldsStr.push( fields[i].name );
			argsStr.push( '?' );
		}

		return "INSERT INTO "+tableName+" ( \n "+
				fieldsStr.join(',')+
				" \n ) VALUES ( \n "+
				argsStr.join(',')+
				" \n );";

},

"SQL_Update":function(){
		var fields=genFields($("sql_zone").value);
		var tableName=getTableName($("sql_zone").value);

		var fieldsStr=[];

		for (var i=0;i<fields.length ;i++ ){
			fieldsStr.push( fields[i].name + " = ? " );
		}

		return "UPDATE "+tableName+" SET \n "+
				fieldsStr.join(',')+
				" ;";

},

"SQLBD_addArgs":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);
	var var_

	var returnStr=[];

	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( C_Context.varName_sqlbd +".addArg("+ 
						C_Context.varName_vo+"."+fields[i].getterName+"() );" );
	}
	return returnStr.join("\r\n");
},

"VO_Set_FromResultSet":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];

	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( C_Context.varName_vo+"."+fields[i].setterName+"("+ 
						C_Context.varName_rs+".get"+fields[i].type+"(\""+fields[i].name+"\"));" );
	}
	return returnStr.join("\r\n");
},

/* 生成json串 */
"getJsonStr":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	var j = fields.length-1;
	returnStr.push("//生成json串");
	
	returnStr.push("StringBuffer json = new StringBuffer();\r\n");
	returnStr.push("json.append(\"{\")");
	for (var i=0;i<fields.length ;i++ ){
		if(i==j){
				 returnStr.push("\t.append(\"'"+fields[i].codeName+
			 				"':'\").append(" +C_Context.varName_vo+"."+
			 				fields[i].setterName+"()"+").append(\"'\")" ); 
		}else{
				 returnStr.push("\t.append(\"'"+fields[i].codeName+
				 			"':'\").append(" +C_Context.varName_vo+"."+
				 			fields[i].setterName+"()"+").append(\"',\")" ); 
		}		
	}
	returnStr.push("\t.append(\"'}\");\r\n");
	returnStr.push("return json.toString();");
	
	return returnStr.join("\r\n");
},

/* 返回函式解析data */
"checkCallBack":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("function checkCallBack(data){");
	returnStr.push("var a = eval(\"(\" + data + \")\");");
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( "document.getElementById(\""+fields[i].codeName+"\").innerHTML=a."+fields[i].codeName+";");
	}
	returnStr.push("$(\"#searchDealerDiv02\").slideDown(1000);");
	returnStr.push("}");
	return returnStr.join("\r\n");
},
/* 顯示table表單 */
"showInfo":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	
	returnStr.push("<fieldset>");
	returnStr.push("<table align=\"center\"  style=\"font-size:12px\" cellpadding=\"5px\" cellspacing=\"5px\">");
	returnStr.push("<tr>");
	
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( "<td class=\"\">"+fields[i].codeName+":</td><td><div id=\""+fields[i].codeName+"\"></div></td>");
	}
	returnStr.push("</tr>");
	returnStr.push("</table>");
	returnStr.push("</fieldset>");
	return returnStr.join("\r\n");
},
/* 賦空值函式(jsp) */
"setNull":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("//返回函式--空處理");
	returnStr.push("function goback(){");
	
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( "document.getElementById(\""+fields[i].codeName+"\").value=\"\";");
	}
	returnStr.push("}");
	
	return returnStr.join("\r\n");
},
/* SQL的結果集設定資料 */
"setSqlRs":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);

	var returnStr=[];

	returnStr.push("/**");
	returnStr.push("\t以SQL的結果集設定資料");
	returnStr.push("*/");
	
	returnStr.push("public void setAttribute(ResultSet resultSet) throws SQLException {");
	returnStr.push("\tResultSetMetaData metaData = resultSet.getMetaData();");
	returnStr.push("\tfor(int i=1;i<=metaData.getColumnCount();i++) {");
	returnStr.push("\t\tString columnName = metaData.getColumnName(i).toLowerCase();");
	for (var i=0;i<fields.length ;i++ ){
		if(i==0){
			returnStr.push("\t\tif(columnName.intern()==\""+fields[i].name+"\".intern())");
			returnStr.push("\t\t\t"+fields[i].codeName+" = "+"nvl(resultSet.getString(i));");
		}else{
			returnStr.push("\t\telse if(columnName.intern()==\""+fields[i].name+"\".intern())");
			returnStr.push("\t\t\t"+fields[i].codeName+" = "+"nvl(resultSet.getString(i));");
		}
		
	}
	returnStr.push("\t\t}");
	returnStr.push("\t}");
	
	
	return returnStr.join("\r\n");
},

/* ajax仿谷歌自動補齊(jsp) */
"ajaxGoogle":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("$.ajax({");
	returnStr.push("url:'queryByNum.do?method=dosearch',");
	returnStr.push("type:'post',");
	returnStr.push("data:'&querybystunum='+querybystunum+'&querybyname='+querybyname,");
	returnStr.push("success:function(data,textStatus){");
	returnStr.push("var a = eval(\"(\"+data+\")\");");
	returnStr.push("if(a.stunum != '0') {");
	returnStr.push("errorMessage2.innerHTML =\"\";");
	returnStr.push("sending.style.visibility=\"visible\";");
	returnStr.push("window.setTimeout(\"clearWait()\",500);");
	
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( "$(\"#"+fields[i].codeName+"\").html(a."+fields[i].codeName+");");
	}
	returnStr.push(");");
	
	returnStr.push("errorMessage2.innerHTML = '<font color=\"red\" size=\"-1\">您要查詢的資料不存在,請確認!</font>';");
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( "$(\"#"+fields[i].codeName+"\").html(\"\");");
	}
	returnStr.push("errorMessage2.style.display = 'block';");
	returnStr.push("document.getElementById(\"querybystunum\").innerText=\"\";");
	returnStr.push("document.getElementById(\"querybystunum\").focus();");
	returnStr.push("}");
	returnStr.push("}");
	returnStr.push("});");
	return returnStr.join("\r\n");
},

/* request獲取頁面引數(jsp) */
"request_getParameter":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("//request獲取頁面引數");
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push("String "+fields[i].codeName+" = "+"nvl(request.getParameter(\""+fields[i].codeName+"\").trim());"); 
	}
	
	return returnStr.join("\r\n");
},

/* js請求action拼引數 */
"js_action":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("/**");
	returnStr.push("\t查詢提交url請求引數");
	returnStr.push("*/");
	returnStr.push("function doSearch(webpath)");
	returnStr.push("{");
	returnStr.push("\tvar url = webpath+'/oss/CusInfoAction.do?';");
	returnStr.push("\t//url += '&OperType=search';");
	
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( "\tif (document.getElementById('"+fields[i].codeName+"').disabled != true && document.getElementById('"+fields[i].codeName+"').value != '') {");
		returnStr.push("\t\turl += '&"+fields[i].codeName+"=' + document.getElementById('"+fields[i].codeName+"').value;");
		returnStr.push("\t}");
	}
	returnStr.push("\tparent.employeelist.location.href = url;");
	returnStr.push("}");
	
	return returnStr.join("\r\n");
},

/* action封裝頁面引數(java) */
"java_action":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("//得到頁面的引數");
	returnStr.push("String queryInfo = \"\";");
	for (var i=0;i<fields.length ;i++ ){
		returnStr.push("queryInfo += \"&"+fields[i].codeName+"=\"+"+fields[i].getterName+";"); 
	}
	returnStr.push("request.setAttribute(\"queryInfo\", queryInfo);");
	return returnStr.join("\r\n");
},

/* where條件處理 */
"whereAddJava":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=[];
	returnStr.push("//	");

	for (var i=0;i<fields.length ;i++ ){
		returnStr.push("if("+fields[i].codeName+"!=null && !"+fields[i].codeName+".equals(\"\")){\n"+
				"\tbuf.append(\" AND "+fields[i].codeName+" = '\").append("+fields[i].codeName+
				").append(\"'\");\n"+"}\n"); 
	}
	
	return returnStr.join("\r\n");
},

//C_Context['varName_stmt']
//pstmt.setXXX(X,getter)

"Stmt_Set_FromVO":function(){
	var fields=genFields($("sql_zone").value);
	var tableName=getTableName($("sql_zone").value);


	var returnStr=["int argsIdx=1;"];

	for (var i=0;i<fields.length ;i++ ){
		returnStr.push( C_Context.varName_stmt+".set"+fields[i].type+"( argsIdx++,"+ 
						C_Context.varName_vo+"."+fields[i].getterName+"() );" );
	}
	return returnStr.join("\r\n");
},


"_END":function(){return "OK";}
};

// VO_Property , SQL_Insert , SQL_Update , VO_Set_FromResultSet


       
function test(){
		for (var key in CodeGen ){
			alert(key+"\n\n"+CodeGen[key]());
		}
}
                            

function doGenMain(optype){
	try{
		$("dest").value=CodeGen[optype]();
	
		HighlightAll("dest");
	}catch (e){
		if (!confirm("發生異常,可能是由於sql語句不符合格式,請諮詢本工具的開發人員.\n\n"+e.description +"\n\n 忽略異常資訊嗎?") ){
			throw e;	
		}
	}

}

function init(){


};


html

<body style='font-size:12px' onLoad="init();">
	<hr/>
	<center><h3>程式碼生成器-ardo</h3></center>
	<hr/>
<fieldset>
	<legend>[阿杜]</legend> 
<table width="100%" border="0">
<tr>
	<td style="width:400px">
	<B>要轉換的SQL(建表語句):</B><br>
<textarea id='sql_zone' rows="30" style="width:400px">
create table OSS_USERINFO
(
  USER_ID   NUMBER(20) not null,
  USER_NAME VARCHAR2(64) not null,
  AGE      NUMBER(3),
  GENDER   VARCHAR2(2),
  BIRTHDAY DATE,
  STATUS   NUMBER(1),
  SCHOOL   VARCHAR2(20),
  IF_VALIDATION NUMBER(1),
  GOODS_ID NUMBER(20),
  ACC_FEE  NUMBER(10),
  constraint PK_OSS_USERINFO primary key (USERID)
)
</textarea>
	</td>
	<td valign="top">
	<button href="#" οnclick='test();return false;' style="width:70px;">測試(test)</button><br/><br/>
	<button href="#" onClick="doGenMain('VO_Property');return false;"> --生成屬性(<span>VO</span>)</button><br/>
	<button href="#" onClick="doGenMain('VO_Getter');return false;"> --生成getter方法(<span>VO</span>)</button><br/>
	<button href="#" onClick="doGenMain('VO_Setter');return false;"> --生成setter方法(<span>VO</span>)</button><br/>

	<button href="#" onClick="doGenMain('SQL_Select');return false;"> --Select(<span>SQL</span>)</button><br/>
	<button href="#" onClick="doGenMain('SQL_Insert');return false;"> --Insert(<span>SQL</span>)</button><br/>
	<button href="#" onClick="doGenMain('SQL_Update');return false;"> --Update(<span>SQL</span>)</button><br/>
	<button href="#" onClick="doGenMain('SQLBD_addArgs');return false;">--VO向sqlBuilder設參(<span>JAVA</span>)</button><br/>

	<button href="#" onClick="doGenMain('VO_Set_FromResultSet');return false;">--VO.Set_結果集(<span>JAVA</span>)</button><br/>
	<button href="#" onClick="doGenMain('Stmt_Set_FromVO');return false;">--Stmt.Set_FromVO(<span>JAVA</span>)</button><br/>
	<button href="#" onClick="doGenMain('getJsonStr');return false;">--生成json串(<span>JAVA</span>)</button><br/>
	<button href="#" onClick="doGenMain('checkCallBack');return false;">--返回方法解析data(<span>JSP</span>)</button><br/>
	<button href="#" onClick="doGenMain('showInfo');return false;">--顯示table表單(<span>JSP</span>)</button><br/>
	<button href="#" onClick="doGenMain('setNull');return false;">--賦空值函式(<span>JSP</span>)</button><br/>
	<button href="#" onClick="doGenMain('setSqlRs');return false;">--SQL的結果集設定資料(<span>VO</span>)</button><br/>
	<button href="#" onClick="doGenMain('ajaxGoogle');return false;">--ajax仿谷歌自動補齊(<span>JSP</span>)</button><br/>
	<button href="#" onClick="doGenMain('request_getParameter');return false;">--request獲取頁面引數(<span>JSP</span>)</button><br/>
	<button href="#" onClick="doGenMain('js_action');return false;">--js請求action拼引數(<span>JSP</span>)</button><br/>
	<button href="#" onClick="doGenMain('java_action');return false;">--action封裝頁面引數(<span>JAVA</span>)</button><br/>
	<button href="#" onClick="doGenMain('whereAddJava');return false;">--where條件處理(<span>JAVA</span>)</button><br/>
	
	


	</td>
	<td>
		<B>轉換結果:</B><br>
		<textarea id='dest' name='dest' rows=30 style="width:600px"></textarea>
	</td>
</tr>
</table>
</fieldset>



相關文章