swing实现的sql查询ui简易实现

package swing.sqlhelper;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;<pre name="code" class="java">package swing.sqlhelper;

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.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class JdbcBase {

	private static Log logger = LogFactory.getLog(JdbcBase.class);
	private static String clazz = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/test";
	private static String  user = "root";
	private static String  password = "123456";
	private static String  param1 = "characterEncoding";
	private static String  value1 = "utf8";
	private static Properties properties = new Properties();
	
	private static Connection connection = null;
	
	static {
		properties.put("user", user);
		properties.put("password", password);
		properties.put(param1,value1);
	}
	
	public static Connection getConn(String url,String clazz, String user,String passwrod) 
			throws Exception {
		
		Connection  conn = null;
		logger.debug("url:" +url);
		logger.debug("clazz:" +clazz);
		logger.debug("user" +user);
		logger.debug("passwrod:" +passwrod);

		try {
			Class.forName(clazz);
			conn = DriverManager.getConnection(url, user,passwrod);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		} 
		return conn;
	}
	
	public static Connection getConn(String url,String clazz,Properties properties)
			throws Exception {
		
		logger.debug("url:" +url);
		logger.debug("clazz:" +clazz);
		if(properties != null) {
			for(Object key : properties.keySet()) {
				logger.debug(""+key+" : " +properties.getProperty(key.toString()));
			}
		}
		
		Connection  conn = null;
		try {
			Class.forName(clazz);
			conn = DriverManager.getConnection(url, properties);
		}  catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return conn;
	}

	
	public static Statement getStatement(Connection conn) throws SQLException {
		
		Statement statement = null;
		try {
			statement = conn.createStatement();
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return statement;
	}
	
	public static PreparedStatement getPreStatement(Connection conn,String sql) throws SQLException {
		
		PreparedStatement statement = null;
		try {
			statement = conn.prepareStatement(sql);
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return statement;
	}
	
	public static ResultSet query(Connection conn,String sql) throws SQLException {
		
		ResultSet rs = null;
		Statement stmt  = null;
		try {
			stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
                    } catch (SQLException e) {
                    logger.error(e.getMessage(), e);
                    throw e;
                    }
                    return rs;
            }
    
    public static boolean execute(Connection conn,String sql) throws SQLException {
    
            boolean isSuccess = false;
            Statement stmt  = null;
            try {
            stmt = conn.createStatement();
            isSuccess = stmt.execute(sql);
            } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            throw e;
            }
            return isSuccess;
            }
    
    
    public static List<List<String>> parseResultSet(ResultSet rs) throws SQLException {
    
            List<List<String>> result = new ArrayList<List<String>>();
            try {
            List<String> columnNames = new ArrayList<String>();
            ResultSetMetaData metaData = rs.getMetaData();
            int columns = metaData.getColumnCount();
            for(int i=1;i<=columns;i++) {
            columnNames.add(metaData.getColumnName(i));
            }
            result.add(columnNames);
            while(rs.next()) {
            List<String> contentRow = new ArrayList<String>();
            for(int i=1;i<=columns;i++) {
            contentRow.add(rs.getString(i));
            }
            result.add(contentRow);
            }
    
            } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            throw e;
            }
            return result;
            }
    
    
    public static Connection getConnection() {
            return connection;
            }
    
    
    public static void setConnection(Connection connection) {
            JdbcBase.connection = connection;
            }
    
            }
    


简易菜单栏:

import java.awt.Menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Memu extends JMenuBar{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1260052538691158115L;

	private Log logger = LogFactory.getLog(Menu.class);
	
	private JMenu menu = null;
	private JMenuItem newConnItem = null;
	private JMenuItem exitItem = null;
	private Dialog dialog = null;
	private JFrame frame = null;
	
	public Memu() {
	}
	
	public Memu(JFrame frame) {
		this.frame = frame;
		init();
		addListener();
	}
	
	public void init() {
		menu = new JMenu("file");
		newConnItem = new JMenuItem("new connection");
		exitItem = new JMenuItem("exit");
		menu.add(newConnItem);
		menu.add(exitItem);
		
		dialog = new Dialog(frame);
		this.add(menu);
	}
	
	public void addListener() {
		
		newConnItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				logger.info("open the new connection dialog..");
				dialog.getDialog().setVisible(true);
			}
		});
		
		exitItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				logger.info("this pragram will be exit...");
				Connection  conn = dialog.getConnection();
				if(conn != null) {
					try {
						conn.close();
						conn = null;

					} catch (SQLException e1) {
						logger.info(e1.getMessage(),e1);
					}
				}
				System.exit(0);
			}
		});
	}

	public Dialog getDialog() {
		return dialog;
	}

	public void setDialog(Dialog dialog) {
		this.dialog = dialog;
	}

}

主界面:

 
package swing.sqlhelper;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;


public class MainFrame extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = -854194571915108287L;

	private Log logger = LogFactory.getLog(MainFrame.class);
	
	private JSplitPane splitPane = null;
	private Memu memu = null;
	private JTextArea queryArea = null;
	private JTextArea resultArea = null;
	private JTable table = null;
	private JPanel tablePane = null;
	private Connection connection = null;

	MainFrame() {
		logger.info("this program will be starting...");
		init();
		initPanel();
		addListener();
		initFrame();
	}
	
	public void init() {
		memu = new Memu(this);
		queryArea = new JTextArea();
		resultArea = new JTextArea();
		tablePane = new JPanel();
		resultArea.setEditable(false);
	}
	
	public void initPanel(){
		JTabbedPane resultTab = new JTabbedPane(JTabbedPane.TOP);
		table = new JTable();
//		tablePane.add(table.getTableHeader(), BorderLayout.NORTH);
		tablePane.add(table);
		resultTab.addTab("script output", resultArea);
		resultTab.addTab("query result", tablePane);
		splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
				queryArea, resultTab);

	}
	
	public void initFrame() {
		this.setJMenuBar(memu);
		this.getContentPane().add(splitPane, BorderLayout.CENTER);
		setSize(1000, 800);
		setTitle("sql helper");
		setLocationRelativeTo(null);
		setVisible(true);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		this.addWindowListener(new WindowAdapter() {
			@SuppressWarnings("unused")
			public void WindowClosing(WindowEvent e) {
				logger.info("this program will be exit....");
				dispose();
				System.exit(0);
			}

			@Override
			public void windowClosed(WindowEvent e) {
				logger.info("this program will be exit....");
				dispose();
				System.exit(0);
			}
			
		});
	}
	
	public void addListener() {
		queryArea.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) {
			}
			@Override
			public void keyReleased(KeyEvent e) {
			}
			@Override
			public void keyPressed(KeyEvent e) {
				
				if(e.getKeyCode() == KeyEvent.VK_ENTER
				&& e.isControlDown()) {
					logger.debug("start to execute sql....");
					connection = memu.getDialog().getConnection();
					if(connection == null) {
						logger.debug("connection null,please connect.");
						return;
					}
					String sql = queryArea.getSelectedText().trim();
					logger.debug("sql:" +sql);
					if(sql.toUpperCase().startsWith("SELECT")) {
						try {
							List<List<String>> list = 
									JdbcBase.parseResultSet(JdbcBase.query(connection, sql));
							TableModel model = initTable(list, list.size());
							table.setModel(model);
						} catch (SQLException e1) {
							logger.error(e1.getMessage(), e1);
						}
					}
					else {
						try {
							JdbcBase.execute(connection, sql);
						} catch (SQLException e1) {
							logger.error(e1.getMessage(), e1);
						}
					}
				}
			}
			public  TableModel initTable(List<List<String>> list, int row)
			  {
			    String[][] data = convertListToDoubleArray(list, row);
			    TableModel tableModel = new DefaultTableModel(data, list.get(0).toArray());
			    return tableModel;
			  }
			
			public  String[][] convertListToDoubleArray(List<List<String>> list, int row)
			  {
			    if (list == null) return null;

			    if (row > list.size()) {
			    	row = list.size();
			    }
			    
			    int length = (list.get(0)).size();
			    String[][] doubleArray = new String[row][length];
			    List list1 = null;
			    for (int i = 0; i < row; i++) {
			      list1 = (List)list.get(i);
			      for (int j = 0; j < length && j<list1.size(); j++) {
			        doubleArray[i][j] = ((String)list1.get(j));
			      }
			    }
			    return doubleArray;
			  }
			
		});
	}

	public static void main(String[] args) {
		
		PropertyConfigurator.configure("lib/log4j.properties");
		new MainFrame();
	}
	

}

建立连接对话框:

package swing.sqlhelper;


import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;


import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;




public class Dialog {


private static Log logger = LogFactory.getLog(Dialog.class);

private JDialog dialog = null;
private JFrame frame = null;
private JLabel nameLabel = null;
private JLabel userLabel = null;
private JLabel passwordLabel = null;
private JLabel urlLabel = null;
private JLabel classLable = null;
private JLabel propertiesLable = null;


private JTextField nameField = null;
private JTextField userField = null;
private JTextField passwordField = null;
private JTextField urlField = null;
private JTextField classField = null;


private JTextArea propertiesArea = null;

private JButton connButton = null;
private JLabel conInfoLabel = null;

private Connection connection = null;
private int dialogWidth = 800;
private int dialogHight = 600;
private int screenWidth = 0;
private int screenHight = 0;
private int startX = 450;
private int startY = 300;
public Dialog() {

}

public Dialog(JFrame frame) {
Dimension screensize=Toolkit.getDefaultToolkit().getScreenSize(); 
// this.screenWidth = screensize.width;
// this.screenHight = screensize.height;
// startX = screenWidth/2 - dialogWidth/2;
// startY = screenHight/2 - dialogHight/2;


this.frame = frame;
init();
setBounds();
addListener();
initDialog();
}

public void init() {
nameLabel = new JLabel("name");
userLabel = new JLabel("user");
passwordLabel = new JLabel("password");
urlLabel = new JLabel("url");
classLable = new JLabel("class");
propertiesLable = new JLabel("properties");

nameField = new JTextField("test");
userField = new JTextField("root");
passwordField = new JTextField("123456");
urlField = new JTextField("jdbc:mysql://localhost:3306/test");
classField = new JTextField("com.mysql.jdbc.Driver");
propertiesArea = new JTextArea();

connButton = new JButton("connection");
conInfoLabel = new JLabel("1");
dialog = new JDialog(frame, false);
}

public void setBounds() {
int width = 100;
int hight = 50;
int widthSize = 100;
int hightSize = 50;
int temstartX = startX - 300;
int temstartY = startY - 300;
nameLabel.setBounds(temstartX+width, temstartY+hight,widthSize,hight);
userLabel.setBounds(temstartX+width, temstartY+2*hight,widthSize,hight);
passwordLabel.setBounds(temstartX+width, temstartY+3*hight,widthSize,hight);
urlLabel.setBounds(temstartX+width, temstartY+4*hight,widthSize,hight);
classLable.setBounds(temstartX+width, temstartY+5*hight,widthSize,hight);
propertiesLable.setBounds(temstartX+width, temstartY+6*hight,widthSize,hight);
conInfoLabel.setBounds(temstartX+width, temstartY+9*hight,widthSize,hight);


nameField.setBounds(temstartX+3*width, temstartY+hight,widthSize,hight);
userField.setBounds(temstartX+3*width, temstartY+2*hight,widthSize,hight);
passwordField.setBounds(temstartX+3*width, temstartY+3*hight,widthSize,hight);
urlField.setBounds(temstartX+3*width, temstartY+4*hight,widthSize*3,hight);
classField.setBounds(temstartX+3*width, temstartY+5*hight,widthSize*3,hight);
propertiesArea.setBounds(temstartX+3*width, temstartY+6*hight,widthSize*3,hight*2);
connButton.setBounds(temstartX+3*width, temstartY+9*hight,widthSize,hight);


}
public void initDialog() {

Container container = dialog.getContentPane();
container.setLayout(null);
container.add(nameLabel);
container.add(userLabel);
container.add(passwordLabel);
container.add(urlLabel);
container.add(classLable);
container.add(propertiesLable);
container.add(nameField);
container.add(userField);
container.add(passwordField);
container.add(urlField);
container.add(classField);
container.add(propertiesArea);
container.add(connButton);
container.add(conInfoLabel);
dialog.setTitle("new connection");
dialog.setBounds(startX, startY, dialogWidth, dialogHight);
// setLocationRelativeTo(null);
dialog.setVisible(false);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@SuppressWarnings("unused")
public void WindowClosing(WindowEvent e) {
logger.info("shutdown the dialog...");
System.exit(0);
}
});
}
public void addListener() {
connButton.addActionListener(new ConnActionListener());
}

class ConnActionListener implements ActionListener {


String name = "";
String user = "";
String password = "";
String url = "";
String clazz = "";
String otherProperties = "";
Properties properties = new Properties();
public static final String lineSplit = "\n";
public static final String keyValueSplit = "=";

@Override
public void actionPerformed(ActionEvent e) {
conInfoLabel.setVisible(false);
name = nameField.getText().trim();
user = userField.getText().trim();
password = passwordField.getText().trim();
url = urlField.getText().trim();
clazz = classField.getText().trim();
otherProperties = propertiesArea.getText();
if(properties == null) {
properties = new Properties();
}
properties.put("user", user);
properties.put("password", password);


Map<String,String>  otherMap = null;
logger.info("otherProperties:" + otherProperties);
otherMap = parseStr(otherProperties);
logger.info("otherMap:" + otherMap);


properties.putAll(otherMap);

try {
if(connection != null) {
connection.close();
connection = null;
logger.info("the connection has no closed,so will close before get another.");


}
connection = JdbcBase.getConn(url, clazz, properties);
logger.info("succeessfull to get a connection.: "+ connection);
conInfoLabel.setText("succeessfull to get a connection.");
conInfoLabel.setVisible(true);
Thread.sleep(1000);
conInfoLabel.setVisible(false);
dialog.setVisible(false);

catch (Exception ee) {
logger.error(ee.getMessage(), ee);
conInfoLabel.setText(ee.getMessage());
conInfoLabel.setVisible(true);
}
}


private Map<String,String> parseStr(String str) {

Map<String,String>  resMap = new HashMap<String,String>();
if(str == null || str.isEmpty()) {
return resMap;
}
String[] lines = str.split(lineSplit);
for(String line : lines) {
if(line == null || line.isEmpty()
|| !line.contains(keyValueSplit)) {
logger.info("line:"+line+"\ncontinue");
continue;
}

String[] keyvalues = str.split(keyValueSplit); 
if(keyvalues.length != 2) {
logger.info("line:"+line+"\ncontinue");
continue;
}
if(keyvalues[0] == null || keyvalues[0].isEmpty() ||
keyvalues[1] == null || keyvalues[1].isEmpty()) {
logger.info("line:"+line+"\ncontinue");
continue;
}
resMap.put(keyvalues[0].trim(), keyvalues[1].trim());

}
return resMap;

}

}


public Connection getConnection() {
return connection;
}


public void setConnection(Connection connection) {
this.connection = connection;
}


public JDialog getDialog() {
return dialog;
}


public void setDialog(JDialog dialog) {
this.dialog = dialog;
}

}

发布了8 篇原创文章 · 获赞 3 · 访问量 1023

猜你喜欢

转载自blog.csdn.net/jaemy2011/article/details/52772855