`
kevin_wanwei
  • 浏览: 117684 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

一个非常有用工具软件

阅读更多

这个小工具非常有用,它可以将数据库表中的字段生成对应的JavaBean,可以自动生成插入和更新select语句,还可以生成对应xml文件,解析xml文件的功能,是WEB开发中非常有用的小工具软件。

package com.bperp;
/*
 * Created on 2005-10-9
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author  Kevin
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
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.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.StringTokenizer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;



@SuppressWarnings("serial")
public class tableTojava extends JFrame {
	private JPanel southpanel;

	private JButton createbutton;

	private JButton sqlbutton;

	private JButton readbutton;

	private JButton insertbutton;

	private JButton updatebutton;

	private JButton jspbutton;
	
	private JButton xmlbutton;
	
	private JButton xmlToDB;

	private Container con;

	private JPanel northpanel;

	private JLabel drivertext;

	private JTextField driver;

	private JLabel urltext;

	private JTextField url;

	private JLabel usertext;

	private JTextField user;

	private JLabel passwordtext;

	private JPasswordField password;

	private JButton conn;

	private JButton exit;

	public java.awt.List tablelist;

	private JTextArea text;

	private JLabel dirtext;

	private JTextField dir;

	private JButton zhengguiInsert;

	private JButton zhengguiUpdate;

	public tableTojava() {
		this.setSize(500, 500);
		this.setTitle("表到JAVABEAN转换小程序");
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		init();
	}

	public void init() {
		southpanel = new JPanel();
		readbutton = new JButton("生成Select语句");
		insertbutton = new JButton("生成Insert语句");
		updatebutton = new JButton("生成update语句");
		sqlbutton = new JButton("生成sql column");
		createbutton = new JButton("生成JAVABEAN");
		jspbutton = new JButton("生成jsp——update页面");
		zhengguiInsert = new JButton("生成jsp—正规—Insert页面");
		zhengguiUpdate = new JButton("生成jsp—正规—Update页面");
		xmlbutton=new JButton("生成xml文件");
		xmlToDB=new JButton("将xml文件写入数据库");
		conn = new JButton("连接数据库");
		exit = new JButton("退出");
		southpanel.setLayout(new GridLayout(4, 4));
		southpanel.add(conn);
		southpanel.add(createbutton);
		southpanel.add(sqlbutton);
		southpanel.add(readbutton);
		southpanel.add(insertbutton);
		southpanel.add(updatebutton);
		southpanel.add(jspbutton);
		southpanel.add(zhengguiInsert);
		southpanel.add(zhengguiUpdate);
		southpanel.add(xmlbutton);
		southpanel.add(xmlToDB);
		southpanel.add(exit);
		exit.setToolTipText("Exit......");
		exit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		con = this.getContentPane();
		con.add(southpanel, BorderLayout.SOUTH);
		northpanel = new JPanel();
		northpanel.setLayout(new GridLayout(5, 2));
		drivertext = new JLabel("输入驱动程序名字");
		driver = new JTextField(30);
		northpanel.add(drivertext);
		northpanel.add(driver);
		urltext = new JLabel("输入要连接的URL");
		url = new JTextField(50);
		northpanel.add(urltext);
		northpanel.add(url);
		usertext = new JLabel("输入用户名");
		user = new JTextField(10);
		northpanel.add(usertext);
		northpanel.add(user);
		passwordtext = new JLabel("输入密码");
		password = new JPasswordField(10);
		northpanel.add(passwordtext);
		northpanel.add(password);
		dirtext = new JLabel("输入你要保存JAVABEAN的目录");
		dir = new JTextField(20);
		northpanel.add(dirtext);
		northpanel.add(dir);
		driver.setText("com.mysql.jdbc.Driver");
		url.setText("jdbc:mysql://192.168.1.201:3306/bperp");
		user.setText("root");
		password.setText("bpcrm");
		tablelist = new java.awt.List();
		text = new JTextArea(10, 30);
		JScrollPane panel = new JScrollPane(text);
		text.setLineWrap(true);
		con.add(panel, BorderLayout.CENTER);
		con.add(tablelist, BorderLayout.WEST);
		con.add(northpanel, BorderLayout.NORTH);
		sqlbutton.addActionListener(new SqlAction());
		readbutton.addActionListener(new ReadAction());
		insertbutton.addActionListener(new InsertAction());
		updatebutton.addActionListener(new UpdateAction());
		createbutton.addActionListener(new CreateAction());
		jspbutton.addActionListener(new jspAction());
		conn.addActionListener(new ConnAction());
		tablelist.addActionListener(new ChooseAction());
		zhengguiInsert.addActionListener(new zhengInsertAction());
		zhengguiUpdate.addActionListener(new zhengguiUpdateAction());
		xmlbutton.addActionListener(new writerXMLAction());
		xmlToDB.addActionListener(new readXmlToDB());
	}
	private class readXmlToDB implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			text.setText("");
				File f=new File("d:\\"+tablelist.getSelectedItem()+".xml");
				 SAXReader reader = new SAXReader(); 
				   try {
					Document doc = reader.read(f);
					Element root = doc.getRootElement();
					Element baseInfo=root.element("BaseInfo");
					String componentid=baseInfo.attributeValue("componentid");
					String componentname=baseInfo.attributeValue("componentname");
					Iterator it=root.elementIterator();
					while(it.hasNext()){
						Element child=(Element)it.next();
						if(!(child.getName().equals("BaseInfo"))){
							String sub=child.attributeValue("simname");
							String obj=child.attributeValue("fieldname");
							Random ran=new Random();
							int a=ran.nextInt();
							int cid=Integer.parseInt(componentid);
							String id=System.currentTimeMillis()+""+a;
							if(hasRecord(cid,obj)){
								continue;
							}
							insertToDB(componentid,componentname,sub,id,obj);
							System.out.println(sub);
						}
						
					}
					text.setText("d:\\"+tablelist.getSelectedItem()+".xml文件成功写入数据库");
				} catch (Exception e1) {
					text.setForeground(new Color(255,0,0));
					text.setText("d:\\"+tablelist.getSelectedItem()+".xml文件写入数据库失败"+"\n"+e1.getMessage());
					e1.printStackTrace();
				} 

			
		}
		private void insertToDB(String componentid,String componentname,String subject,String id,String objectid)throws Exception{
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText()+"?useUnicode=true&characterEncoding=GBK",
						user.getText(), String.copyValueOf(password.getPassword()));
				String sql="INSERT INTO comm_property VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
				PreparedStatement ps=conn.prepareStatement(sql);
				int p=1;
				ps.setString(p++, id);
				ps.setString(p++, subject);
				ps.setString(p++, "");
				ps.setString(p++, componentid);
				ps.setString(p++, componentname);
				ps.setString(p++, objectid);
				ps.setString(p++, "");
				ps.setDate(p++, java.sql.Date.valueOf("2009-12-02"));
				ps.setDate(p++,  java.sql.Date.valueOf("2009-12-02"));
				ps.setString(p++, "091202");
				ps.setString(p++, "kevin");
				if (ps.executeUpdate() == 0) {
					 throw new Exception("插入错误");
				}
			} catch (Exception e) {
				throw e;
			} 
		}
		private boolean hasRecord(int componentid, String objectid) throws Exception{
			boolean b = false;
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				Class.forName(driver.getText());
				conn = DriverManager.getConnection(url.getText()
						+ "?useUnicode=true&characterEncoding=GBK", user
						.getText(), String.copyValueOf(password.getPassword()));
				String sql = " SELECT * FROM comm_property  a "
						+ " where a.componentid = ? and objectid = ?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, componentid);
				ps.setString(2, objectid);
				rs=ps.executeQuery();
				if(rs.next()){
					b=true;
				}
			} catch (Exception e) {
				throw e;
			}finally{
				try {
					rs.close();
				} catch (SQLException e) {
					throw e;
				}
			}
			return b;
		}

	}
	private class writerXMLAction implements ActionListener{
		public writerXMLAction(){
			
		}
		public void actionPerformed(ActionEvent e) {
			text.setText("");
			 try {
		            XMLWriter writer = null;// 声明写XML的对象
		            OutputFormat format = OutputFormat.createPrettyPrint();
		            format.setEncoding("GB2312");// 设置XML文件的编码格式
		            String filePath = "d:\\"+tablelist.getSelectedItem()+".xml";
		            File file = new File(filePath);
	                Document document = DocumentHelper.createDocument();
	                Element root = document.addElement("TableInfo");
	                Element baseInfo = root.addElement("BaseInfo");
	                baseInfo.addAttribute("TableName", tablelist.getSelectedItem());
	                baseInfo.addAttribute("componentid","");
	                baseInfo.addAttribute("componentname","");
	                java.util.List list = this.getList();
	                Iterator it = list.iterator();
	                while(it.hasNext()){
	                	String str = (String) it.next();
	                	String s[]=str.split(",");
		                Element fieldInfo = root.addElement("FieldInfo");
		                fieldInfo.addAttribute("fieldname",s[1]);
		                fieldInfo.addAttribute("fieldtype",s[0]);
		                fieldInfo.addAttribute("fieldlength",s[2]);
		                fieldInfo.addAttribute("simname","");
	                }
	                writer = new XMLWriter(new FileWriter(file), format);
	                writer.write(document);
	                writer.close();
	                text.setText("生成xml文件成功,文件路径为d:\\"+tablelist.getSelectedItem()+".xml");
			 }catch(Exception e1){
				 text.setForeground(new Color(255,0,0));
				 text.setText("生成xml文件失败"+"\n"+e1.getMessage());
				 e1.printStackTrace();
			 }
			
		}
		private java.util.List getList() throws Exception{
			try {
				java.util.List<String> list = new ArrayList<String>();
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("select * from "
						+ tablelist.getSelectedItem());
				ResultSetMetaData rsmd = rs.getMetaData();
				for (int i = 1; i <= rsmd.getColumnCount(); i++)
					list.add((String) getColumString(i, rs) + ","+rsmd.getColumnName(i)+","+
							rsmd.getColumnDisplaySize(i));
				return list;
			} catch (Exception e) {
				throw e;
			}
			
		}
		
	}
	private class zhengguiUpdateAction implements ActionListener {
		public zhengguiUpdateAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				java.util.List list = this.getList();
				StringBuffer bf = new StringBuffer();
				bf.append("\"update  " + tablelist.getSelectedItem() + " set ");
				Iterator it = list.iterator();
				while (it.hasNext()) {
					String str = (String) it.next();
					bf.append(str + "=" + "\"+" + "\"'\"+" + "value.get"
							+ getFirst(str) + "()" + "+\"',");
				}

				// String str="update student set
				// myid="+"'"+value.getMyid()+"',address="+"'"+value.getAddress()+"',email="+"'"+value.getEmail()+"';
				text.setText(bf.toString());
				// String s=

				// String st= "update student set
				// myid="+"'"+value.getMyid()+"',address="+"'"+value.getAddress()+"',email="+"'"+value.getEmail()+"';

			} catch (Exception ex) {
				ex.printStackTrace();
			}
			

		}

		private java.util.List getList() {
			try {
				java.util.List<String> list = new ArrayList<String>();
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("select * from "
						+ tablelist.getSelectedItem());
				ResultSetMetaData rsmd = rs.getMetaData();
				for (int i = 1; i <= rsmd.getColumnCount(); i++)
					list.add(rsmd.getColumnName(i));
				return list;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	private class zhengInsertAction implements ActionListener {
		public zhengInsertAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				java.util.List list = this.getList();
				StringBuffer bf = new StringBuffer();
				bf
						.append("\" insert into " + tablelist.getSelectedItem()
								+ "(");
				Iterator it = list.iterator();
				while (it.hasNext()) {
					bf.append((String) it.next() + ",");
				}
				bf.append(")");
				bf.append("  values(" + "\"" + "\'");
				Iterator itt = list.iterator();
				while (itt.hasNext()) {
					bf.append("," + "\'" + "\"" + "+value.get"
							+ getFirst((String) itt.next()) + "()" + "+\""
							+ "\'");
				}
				bf.append(")");
				text.setText(bf.toString());
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}

		private java.util.List getList() {
			try {
				java.util.List<String> list = new ArrayList<String>();
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("select * from "
						+ tablelist.getSelectedItem());
				ResultSetMetaData rsmd = rs.getMetaData();
				for (int i = 1; i <= rsmd.getColumnCount(); i++)
					list.add(rsmd.getColumnName(i));
				return list;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

	}

	private class CreateAction implements ActionListener {

		public CreateAction() {

		}

		public void actionPerformed(ActionEvent e) {
			StringBuffer bf = new StringBuffer();
			text.setText("");
			bf.append("import java.io.Serializable;\n\n");
			bf.append("//*对应的表:").append(tablelist.getSelectedItem() + "\n\n");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				String classname = getFirst(tablename.substring(3)) + "Value";
				bf.append("public class " + classname
						+ "  implements Serializable \n { \n");
				ArrayList rsmd = (ArrayList) getColumnNames(rs);

				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					String temp = (String) it.next();
					bf.append("           private  ").append(temp + ";\n");
				}
				bf.append("\n");
				Iterator itt = rsmd.iterator();
				while (itt.hasNext()) {
					String temp = (String) itt.next();
					StringTokenizer st = new StringTokenizer(temp, " ");
					String type = st.nextToken();
					String name = st.nextToken();
					bf.append("          public void set").append(
							getFirst(name)).append("(").append(type)
							.append(" ").append(name).append(")\n");
					bf.append("           {\n");
					bf.append("            ").append("   this." + name).append(
							"=").append(name).append(";\n");
					bf.append("           }");
					bf.append("\n");
					bf.append("          public ").append(type).append(" get")
							.append(getFirst(name)).append("(").append(")\n");
					bf.append("           {\n");
					bf.append("            ").append("   return this.").append(
							name).append(";\n");
					bf.append("           }");
					bf.append("\n");
				}
				bf.append("}");
				text.append(bf.toString());
				String filename = dir.getText() + "\\";
				File f = new File(filename + classname + ".java");
				FileOutputStream out = new FileOutputStream(f);
				out.write(text.getText().getBytes());
				out.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	private class SqlAction implements ActionListener {
		public SqlAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				ArrayList rsmd = (ArrayList) getColumn(rs);
				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					text.append((String) it.next());
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				e.paramString();
			}
		}
	}

	private class ReadAction implements ActionListener {
		public ReadAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				ArrayList rsmd = (ArrayList) getReadColumn(rs);

				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					text.append((String) it.next());
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				e.paramString();
			}
		}
	}

	private class InsertAction implements ActionListener {
		public InsertAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				ArrayList rsmd = (ArrayList) getInsertColumn(rs);

				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					text.append((String) it.next());
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				e.paramString();
			}
		}
	}

	private class UpdateAction implements ActionListener {
		public UpdateAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				ArrayList rsmd = (ArrayList) getUpdateColumn(rs);

				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					text.append((String) it.next());
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				e.paramString();
			}
		}
	}

	private class ChooseAction implements ActionListener {
		public ChooseAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				ArrayList rsmd = (ArrayList) getColumnNames(rs);
				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					text.append((String) it.next() + "\n");
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				e.paramString();
			}
		}
	}

	private class ConnAction implements ActionListener {
		public ConnAction() {
		}

		public void actionPerformed(ActionEvent e) {
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("show tables");
				while (rs.next()) {
					tablelist.add(rs.getString(1));
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public java.util.List getColumnNames(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			for (int i = 1; i <= rsmd.getColumnCount(); i++)
				list.add((String) getColumString(i, rs) + " "
						+ rsmd.getColumnName(i));
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public java.util.List getColumnPara(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			for (int i = 1; i <= rsmd.getColumnCount(); i++)
				list.add("?");
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public java.util.List getColumnPara1(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			for (int i = 1; i <= rsmd.getColumnCount(); i++)
				list.add("\"" + rsmd.getColumnName(i));
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public java.util.List getColumnUpdatePara(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			for (int i = 1; i <= rsmd.getColumnCount(); i++)
				list.add(rsmd.getColumnName(i) + "=?");
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public java.util.List getColumn(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			for (int i = 1; i <= rsmd.getColumnCount(); i++)
				list.add(rsmd.getColumnName(i) + ", ");
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public java.util.List getReadColumn(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			String tablename = tablelist.getSelectedItem();
			String classname = getFirst(tablename.substring(3)) + "Value";
			String strwhile = " Vector mList = new Vector();\n";
			strwhile = " while (rs.next()) { \n ";
			strwhile = strwhile + "	int k = 1;\n";
			strwhile = strwhile + "	" + classname + "	value = new " + classname
					+ "();\n";
			list.add(strwhile);
			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				String sql = "	value.set" + getFirst(rsmd.getColumnName(i))
						+ "(rs.getString(k++));\n";
				list.add(sql);

			}
			list.add("		mList.add(value);\n");
			list.add("}");
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public java.util.List getInsertColumn(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			String tablename = tablelist.getSelectedItem();
			// String classname=getFirst(tablename.substring(3))+"Value";
			String strsql = " String sql = \"\";\n";
			strsql = strsql
					+ " sql = \"INSERT INTO "
					+ tablename
					+ "( \"+"
					+ tablename
					+ "Fields"
					+ "+\" ) VALUES ("
					+ getColumnPara(rs).toString().substring(1,
							getColumnPara(rs).toString().length() - 1)
					+ ")\";\n";
			strsql = strsql + " con = dataSource.getConnection(); \n";
			strsql = strsql + " ps = con.prepareStatement(sql); \n";
			strsql = strsql + " int p=1; \n";
			list.add(strsql);
			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				String sql = "	ps.setString(p++, value.get"
						+ getFirst(rsmd.getColumnName(i)) + "());\n";
				list.add(sql);

			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public java.util.List getUpdateColumn(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			String tablename = tablelist.getSelectedItem();
			// String classname=getFirst(tablename.substring(3))+"Value";
			String strsql = " String sql = \"\";\n";
			strsql = strsql
					+ " sql = \"UPDATE "
					+ tablename
					+ " SET "
					+ getColumnUpdatePara(rs).toString().substring(1,
							getColumnUpdatePara(rs).toString().length() - 1)
					+ " WHERE ****************=? " + "\";\n";
			strsql = strsql + " con = dataSource.getConnection(); \n";
			strsql = strsql + " ps = con.prepareStatement(sql); \n";
			strsql = strsql + " int p=1; \n";
			list.add(strsql);
			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
				String sql = "	ps.setString(p++, value.get"
						+ getFirst(rsmd.getColumnName(i)) + "());\n";
				list.add(sql);

			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private class jspAction implements ActionListener {
		public jspAction() {
		}

		public void actionPerformed(ActionEvent e) {
			text.setText("");
			try {
				Class.forName(driver.getText());
				Connection conn = DriverManager.getConnection(url.getText(),
						user.getText(), String.copyValueOf(password.getPassword()));
				Statement stmt = conn.createStatement();
				String tablename = tablelist.getSelectedItem();
				ResultSet rs = stmt.executeQuery("select * from " + tablename);
				ArrayList rsmd = (ArrayList) getColumnJSP(rs);
				Iterator it = rsmd.iterator();
				while (it.hasNext()) {
					text.append((String) it.next() + "\n");
				}
				rs.close();
				stmt.close();
				conn.close();
			} catch (Exception ex) {
				e.paramString();
			}
		}
	}

	public java.util.List getColumnJSP(ResultSet rs) {
		java.util.List<String> list = new ArrayList<String>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			try {

				for (int i = 1; i <= rsmd.getColumnCount(); i++)
					list.add((String) getColumString(i, rs) + " "
							+ rsmd.getColumnName(i)
							+ " = request.getParameter(\""
							+ rsmd.getColumnName(i) + "\");");

			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}

			String tablename = tablelist.getSelectedItem();
			String classname = getFirst(tablename.substring(3)) + "Value";
			String strwhile = "	" + classname + "	value = new " + classname
					+ "();\n";
			list.add(strwhile);

			try {
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
					String xx = " value.set" + getFirst(rsmd.getColumnName(i))
							+ "(" + rsmd.getColumnName(i) + ");";
					list.add(xx);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object getColumString(int col, ResultSet rs) {
		Object obj = null;
		int type = 0;
		try {
			type = rs.getMetaData().getColumnType(col);
			switch (type) {
			case Types.BIGINT:
			case Types.INTEGER:
			case Types.SMALLINT:
			case Types.TINYINT:
				obj = "int";
				break;
			case Types.DOUBLE:
			case Types.DECIMAL:
			case Types.NUMERIC:
			case Types.FLOAT:
				obj = "double";
				break;
			case Types.DATE:
			case Types.TIMESTAMP:
				obj = "Date";				
				break;
			case Types.CHAR:
			case Types.VARCHAR:
			case Types.LONGVARCHAR:
				obj = "String";
				break;
			default:
				obj = "String";
				break;
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		new tableTojava().setVisible(true);
	}

	public String getFirst(String str) {
		String first = str.substring(0, 1).toUpperCase();
		return first + str.substring(1);
	}

}

 

0
1
分享到:
评论
4 楼 kevin_wanwei 2009-12-03  
将表中的内容导出不是很简单吗,你可以自己尝试去改一下了。我做这个工具也是为了我的项目的需要啊。
3 楼 徐风子 2009-12-03  
以前也写过类似的东西,还自己搞了一套 “代码生成的脚本语言”,(现在想起来现在想起来很汗!)
现在想想,其实不用那么麻烦的,随便用个什么高阶语言(groovy 、scala 或者ruby什么的),十几行代码就搞定了。而且特别易于扩展。
2 楼 gml520 2009-12-03  
谢谢! 不过生成xml只是 表的结构,建议做成可以将数据库中的内容导出到xml文件中的功能。
1 楼 dreaminjava 2009-12-03  
工具呢?没提供??

相关推荐

    快速测试键盘软件-键盘检测工具是一个有用的键盘测试工具软件

    键盘检测工具是一个有用的键盘测试工具软件,利用它可以很快的检测出键盘上键位的好坏,并根据测试参数判定键盘的优劣。对于爱好打字的用户来说,该软件还可以测试你的打字速度呢 键盘检测工具是一个有用的键盘测试...

    最新字节跳动小程序抖音艺术签名小程序源码/艺术签名设计小程序源码 这个小程序是一个非常有用的工具,可以帮助您创建各种各样的艺术

    这个小程序是一个非常有用的工具,可以帮助您创建各种各样的艺术签名,以便在社交媒体平台上展示您的个性和创意。最新字节跳动小程序抖音艺术签名小程序源码/艺术签名设计小程序源码 这个小程序是一个非常有用的...

    一个网络检测非常有用的工具

    这是一个非常好的工具,如果对你有用的话,就赶快拿去用吧

    一个好用的软著代码提取工具软件

    标题中的“软著代码提取工具软件”是一种专为软件著作权(软著)准备的实用工具,它能够帮助用户高效地提取指定目录下的源代码文件内容。这类工具在IT行业中非常有价值,因为它们能够自动化处理大量代码,对于进行...

    非常有用的U盘工具

    工具中可能包含一个轻量级的防病毒软件,可以快速扫描U盘,确保其中的数据安全无虞。 2. **数据备份与恢复**:在意外丢失或格式化U盘后,数据恢复工具可以帮助找回重要文件。这可能是通过扫描U盘的扇区来寻找可恢复...

    常用工具软件PPT 一些电脑常用的工具软件

    【描述】提到的"一些常用工具软件的使用教程"旨在为用户提供一个科普性质的学习平台,让大家了解和掌握这些工具的使用方法。这样的教程对于初学者或者想要提升技能的人来说是非常有价值的,能够帮助他们在日常电脑...

    TCP服务端和TCP客户端工具软件

    客户端首先发送一个SYN(同步)包到服务端,服务端回应一个SYN+ACK(同步确认)包,客户端再回应一个ACK(确认)包,这样就完成了三次握手,建立了可靠的连接。客户端和服务端可以在此连接上双向传输数据,直到一方...

    一个有用的工具——大素数生成器

    标题中的“一个有用的工具——大素数生成器”指的是一个专门用于生成大素数的软件。在密码学中,大素数是构建某些加密算法,尤其是RSA公钥加密算法的关键元素。RSA是一种非对称加密技术,由Ron Rivest、Adi Shamir和...

    非常好用、非常有用的声音合成工具

    标题中的“非常好用、非常有用的声音合成工具”指的是一个能够高效、实用地将文本转换为语音的软件。这种工具在日常生活中有许多应用,比如帮助视障人士阅读电子文本,为有声读物制作提供便利,或者在制作语音导航、...

    基址扫描工具(实用工具软件下载安装包).zip

    描述中的“实用工具软件下载安装包”暗示这可能是一个集合了多种实用工具的软件包,其中包含了基址扫描工具以及可能的其他辅助工具,方便用户一次性下载和安装。这种类型的软件包通常为用户提供便捷,使他们可以一站...

    一些有用小工具合集

    这对于学习编程、理解软件工作机制或者开发新工具的人来说,是一个宝贵的学习资源。 工具集合中的其他可能内容: 1. **系统优化工具**:这类工具可以帮助用户清理无用文件,提高系统性能,如注册表清理工具、磁盘...

    针对PLC加密反馈串口数据分析,非常有用工具,通过软件分析分析很容易得到密码

    针对PLC加密反馈串口数据分析,非常有用工具,通过软件分析分析很容易得到密码

    一些非常有用的小软件

    4. **图片处理工具**:如GIMP,它是免费的图像编辑软件,可以进行图像裁剪、调整、滤镜处理等,对于非专业设计者来说,是一个非常好的替代Photoshop的选择。 5. **下载管理器**:如Internet Download Manager (IDM)...

    FMD工具固件与上位机软件对照表-0316

    FMD工具固件与上位机软件对照表是一个非常有用的技术文档,旨在帮助开发者和工程师更好地理解和使用FMD工具,从而提高开发效率和产品质量。 在该表格的基础上,我们可以总结出以下几个重要的知识点: 1. FMD工具...

    USB 串口适配器修改软件工具

    MAC地址修改可以使你的设备在网络中看起来像是一个不同的设备,这对于测试环境来说非常有用,可以避免因为设备识别问题导致的错误。同时,这也可能用于保护隐私,因为MAC地址可以被用来追踪设备的位置和活动。 ...

    简单实用绿色软件制作工具

    描述中的“可以制作绿色软件的一个小程序,操作非常的简单”说明了该工具的易用性。这表明用户不需要具备高级的编程或系统管理员技能,就能通过这个工具快速将常规软件转换为绿色版。这种简化的过程可以节省时间和...

    简单方便非常有用的抓图软件

    【snagit32】这个文件名可能是该抓图软件的安装程序或者是一个32位版本的程序文件。Snagit是TechSmith公司开发的一款知名的截图和屏幕录制软件,它不仅提供了基础的截图功能,还有强大的编辑工具,如添加文字、形状...

    VB6绿色软件打包工具

    VB6绿色软件打包工具是一种专为Visual Basic 6(VB6)开发的程序设计者设计的实用工具。它允许开发者将他们的VB6应用程序打包成独立...对于那些希望在不同环境下运行VB6应用程序的人来说,这是一个非常实用的解决方案。

Global site tag (gtag.js) - Google Analytics