database table to Java Class conversion tool __ Database

Source: Internet
Author: User
Tags string format stringbuffer
//the tool class can be implemented by automatically generating the corresponding Java entity class 
given a specified database table name.
Package com.iamzken.utils;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.net.URL;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import Java.sql.ResultSetMetaData;
Import java.sql.SQLException;

Import Java.util.Vector;
	public class Db2javaconvertor {private Connection Connection;
	Private PreparedStatement userquery; /*mysql URL's connection string */private static string url = "jdbc:mysql://127.0.0.1:3306/test?useunicode=true&
	Characterencoding=utf-8&useoldaliasmetadatabehavior=true ";
	Account private static String user = "root";
	Password private static String password = "";
	Private vector<string> Vector = new vector<string> ();
	MySQL JDBC Java package driver string private string driverclassname = "Com.mysql.jdbc.Driver";
	The table name in the database String table = "Teacher"; The column name of the database private string[] colnames; Column array group//column name Type array private string[] coltypes;
	Public Db2javaconvertor () {try {//Drive registration Class.forName (DRIVERCLASSNAME); if (connection = null | | connection.isclosed ())//Get link connection = drivermanager.getconnection (URL, user, passwo
		RD);
				catch (ClassNotFoundException ex) {ex.printstacktrace ();
			System.out.println ("Oh,not");
				catch (SQLException e) {e.printstacktrace ();
			System.out.println ("Oh,not");
	} public Connection getconnection () {return Connection;
	public void SetConnection (Connection Connection) {this.connection = Connection;
		public void Doaction () {String sql = ' select * from ' +table;
			try {preparedstatement statement = connection.preparestatement (SQL);
			Gets the metadata of the database ResultSetMetaData metadata = Statement.getmetadata ();
			Number of fields in the database int len = Metadata.getcolumncount ();
			Field name colnames = new String[len+1];
			Field type---> has been converted to the class name in Java Coltypes = new string[len+1]; for (int i= 1;i<=len;i++) {//system.out.println (metadata.getColumnName (i) + ":" +metadata.getcolumntypename (i) + ":" +sqltype2javatype (Metadata.getcolumntypename (i). toLowerCase
				()) + ":" +metadata.getcolumndisplaysize (i));
				Metadata.getcolumndisplaysize (i); Colnames[i] = Metadata.getcolumnname (i); Gets the field name Coltypes[i] = Sqltype2javatype (Metadata.getcolumntypename (i));
		Gets the field type} catch (SQLException e) {e.printstacktrace (); }/* * MySQL's field type translates to Java type * * private string Sqltype2javatype (string sqltype) {if sqltype.equal  
        Signorecase ("bit") {return "boolean");  
        }else if (sqltype.equalsignorecase ("tinyint")) {return "byte";  
        }else if (sqltype.equalsignorecase ("smallint")) {return ' short ';  
        }else if (sqltype.equalsignorecase ("INTEGER")) {return "int";  
        }else if (sqltype.equalsignorecase ("bigint")) {return "long";  
        }else if (sqltype.equalsignorecase ("float")) {return "float"; }else if (Sqltype.equalsignorecase ("decimal") | | sqltype.equalsignorecase ("numeric") | | sqltype.equalsign Orecase ("real") | | Sqltype.equalsignorecase ("Money") | |  
        Sqltype.equalsignorecase ("SmallMoney")) {return "double"; }else if (sqltype.equalsignorecase ("varchar") | | | sqltype.equalsignorecase ("char") | | sqltype.equalsignor Ecase ("nvarchar") | | Sqltype.equalsignorecase ("nchar") | |  
        Sqltype.equalsignorecase ("text")) {return "String"; }else if (sqltype.equalsignorecase ("datetime") | |  
        Sqltype.equalsignorecase ("date") {return "java.util.Date";  
        }else if (sqltype.equalsignorecase ("image")) {return "Blod";  
    return null; /* * Gets the string of the entire class and outputs it as a Java file * */Public StringBuffer Getclassstr () {String className = table.substring (0,1). Touppercas
		E () +table.substring (1); Output class string StringBuffer str = new StrinGbuffer ("");
		Gets the field name of the table type and table name This.doaction ();
		
		Verify if (null = = Colnames && null = coltypes) return null;
		Str.append (This.getclass (). Getpackage () + "; \r\n\r\n");
		Stitching Str.append ("public class" +classname+ "{\ r \ n"); Stitching properties for (int index=1; index < colnames.length; index++) {Str.append getattrbutestring (colnames[index],coltypes[
		Index])); ///Stitching Get,set method for (int index=1; index < colnames.length; index++) {Str.append (getgetmethodstring
			Dex],coltypes[index]));
		Str.append (getsetmethodstring (Colnames[index],coltypes[index));
		} str.append ("}\r\n");
		Output to file String S1 = DB2JavaConvertor.class.getPackage (). GetName (). Replace (".", "\ \");
		String s2 = "src" +file.separator+ "main" +file.separator+ "Java" +FILE.SEPARATOR+S1;  
		String s3 = System.getproperty ("User.dir") +file.separator+s2;
		File File = new file (S3);
		if (!file.exists ()) {file.mkdirs ();

		} BufferedWriter write = null; try {write = new BufferedWriter (new FileWriter (New File (s3+file.separator+classname+ ". Java"));
			Write.write (Str.tostring ());
		Write.close ();
			catch (IOException e) {e.printstacktrace ();
				if (write!= null) try {write.close ();
				catch (IOException E1) {e1.printstacktrace ();
	} return str; /* * Get field String */Public StringBuffer getattrbutestring (string name, String type) {if (!check (Name,type)) {System
			. OUT.PRINTLN ("a property or type is NULL in the class");
		return null;
		};
		String format = String.Format ("Private%s%s;\n\r", New String[]{type,name});
	return new StringBuffer (format); /* * Verify that name and type are legitimate/public boolean check (string name, String type) {if (""). Equals (name) | | Name = = NULL | |
		Name.trim (). Length () ==0) {return false; if ("". Equals (type) | | Type = = NULL | |
		Type.trim (). Length () ==0) {return false;
		
	return true; * * * Gets the Get method string */Private StringBuffer getgetmethodstring (string name, String type) {if (!check (Name,type)) {S Ystem.out.pRintln ("A property or type is NULL in the class");
		return null;
		};
		String methodname = "Get" +gettuofeng (name);
		String format = String.Format ("Public%s%s () {\n\r", new Object[]{type,methodname});
		Format + = String.Format ("Return this.%s;\r\n", New Object[]{name});
		Format + + "}\r\n";
	return new StringBuffer (format);
		///capitalize the first character of the name to private string Gettuofeng (string name) {name = Name.trim ();
		if (Name.length () > 1) {name = name.substring (0, 1). toUpperCase () +name.substring (1);
		}else {name = Name.touppercase ();
	} return name; * * * Gets the field's Get method String */Private Object getsetmethodstring (string name, String type) {if (!check (Name,type)) {Syst
			Em.out.println ("A property or type is NULL in the class");
		return null;
		};
		String methodname = "Set" +gettuofeng (name);
		String format = String.Format ("public void%s (%s) {\n\r", new Object[]{methodname,type,name});
		Format + = String.Format ("this.%s =%s;\r\n", New Object[]{name,name});
		Format + + "}\r\n"; return new StringBuffer (format);
		public static void Main (string[] args) throws IOException {Db2javaconvertor bean = new Db2javaconvertor ();
		System.err.println (Bean.getclassstr ());
		System.out.println (ReflectBean.class.getPackage ());
		System.out.println (ReflectBean.class.getPackage (). GetName ());
System.out.println (ReflectBean.class.getResource (""). GetPath ()); 
File directory = new file ("");//parameter is NULL//String Coursefile = Directory.getcanonicalpath (); 
System.out.println (Coursefile); 
//File F = new file (ReflectBean.class.getResource (""). GetPath ());
System.out.println (f); 
//URL Xmlpath = ReflectBean.class.getClassLoader (). GetResource ("");
System.out.println (Xmlpath);
String S1 = Directory.getabsolutepath ();
	System.out.println (S1);
		/* String s3 = ReflectBean.class.getPackage (). GetName (). Replace (".", "\ \");  
		String s2 = system.getproperty ("User.dir") +file.separator+s3;
 SYSTEM.OUT.PRINTLN (s2); */}}

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.