修正 Swing—SQL测试工具编写

本文关注Swing SQL测试工具的编写要点,包括修饰符的使用范围、文本变量的应用、避免业务逻辑代码混入自动生成的代码、消除冗余参数和代码、正确处理异常、善用Swing内置控件、避免精度损失以及PreparedStatement与Statement的区别。
摘要由CSDN通过智能技术生成

 

注意:

1.修饰符private public  protect的使用范围 当前类,全部类,相同package其子类;静态static 最终final的使用;

2.文本使用变量的形式 如 this.setTitle("SwingSQL测试");

3.自动动生成的代码中间不要写业务逻辑代码

// <editor-fold defaultstate="collapsed" desc="Generated Code"> // </editor-fold>//GEN-END:initComponents

4.注意冗余参数,冗余代码

5.try catch用一层,不要多层,catch后要注意输出异常 如 e.printStackTrace();

6.尽量使用SWIng已有控件

7. D  为 double  不使用为int精度,会导致损失小数点之后的精度,转为doulbe精度将不会

19
19.392
 

public class Main {

	public static void main(String[] args) {
		long l1 = 10000;
		long l2 = 29392;

		System.out.println((l2 - l1)/1000 );
		System.out.println((l2 - l1)/1000D );

	}

}

8.PreparedStatement 和 Statement 的区别:https://blog.csdn.net/qpzkobe/article/details/79283709

 

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package swingsql;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



public class NewJFrame extends javax.swing.JFrame {


	// JDBC driver name and database URL
	//private final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
	private final String DB_URL = "jdbc:mysql://localhost:3306/samp_db?serverTimezone=GMT";

	//  Database credentials
	private String USER = "root";
	private String PASS = "zyl123";


	private final String FILE_PATH = "src/out.txt";
	private final String COMPARED_FILE_PATH = "src/true.txt";
	private final String RESULT_FILE_PATH = "src/result.txt";
	private final String DATA_SQL = "src/data.sql";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Creates new form NewJFrame
	 */
	public NewJFrame() {
		initComponents();
		String title = "SwingSQL测试";
		this.setTitle(title);
		setLocationRelativeTo(null);
	}


	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	//   @SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
	private void initComponents() {

		textUser = new java.awt.TextField();
		textPassword = new java.awt.TextField();
		labUser = new java.awt.Label();
		labPassword = new java.awt.Label();
		textArea = new java.awt.TextArea();
		labStart = new java.awt.Label();
		jBtUser = new javax.swing.JButton();
		jBtPassword = new javax.swing.JButton();
		jBt3Start = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		textUser.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
		textUser.setText("root");


		textPassword.setText("zyl123");


		labUser.setText("数据库");

		labPassword.setText("密码");

		labStart.setText("功能");

		jBtUser.setText("打开目录");
		jBtUser.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jBtPassword.setText("开始比对");
		jBtPassword.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton2ActionPerformed(evt);
			}
		});
		jBt3Start.setText("确认");
		jBt3Start.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton3ActionPerformed(evt);   
			}
		});
		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addGap(0, 52, Short.MAX_VALUE)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
								.addGroup(layout.createSequentialGroup()
										.addComponent(labStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jBtPassword)
												.addComponent(jBtUser))
										.addGap(331, 331, 331))
								.addGroup(layout.createSequentialGroup()
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
												.addComponent(labPassword, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
												.addComponent(labUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
										.addGap(7, 7, 7)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
														.addComponent(textUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
												.addComponent(jBt3Start))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(textArea, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(47, 47, 47))))
				);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(layout.createSequentialGroup()
										.addGap(36, 36, 36)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(labUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(textUser, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(20, 20, 20)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(labPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(jBt3Start))
								.addGroup(layout.createSequentialGroup()
										.addContainerGap()
										.addComponent(textArea, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
						.addGap(49, 49, 49)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(labStart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(jBtUser))
						.addGap(29, 29, 29)
						.addComponent(jBtPassword)
						.addContainerGap(68, Short.MAX_VALUE))
				);

		pack();
	}  // </editor-fold>//GEN-END:initComponents



	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
		textArea.append("打开目录" + "\n");
		getRootPane().setDefaultButton(jBtUser);
		try {
			Desktop.getDesktop().open(new File("src/"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}                                        
	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
		textArea.append("开始比对" + "\n");
		getRootPane().setDefaultButton(jBtPassword);
		long startTime = System.currentTimeMillis();

		try {
			BufferedReader	br = new BufferedReader(new FileReader(FILE_PATH));
			BufferedReader  cbr = new BufferedReader(new FileReader(COMPARED_FILE_PATH));
			BufferedWriter  rbw = new BufferedWriter(new FileWriter(RESULT_FILE_PATH));
			try {
				int lineNum = 1;
				String lineStr = null;
				String brStr = null;
				String cbrStr = null;
				//while循环直到两个文件某个文件为空行
				while((brStr = br.readLine()) != null  &&(cbrStr = cbr.readLine()) != null) 
				{

					if (brStr.equals(cbrStr)) {
						lineStr = "<<<Equal:  " + lineNum + "\n";
					} else
					{
						lineStr = "###NOTEqual:   " + lineNum + "\n";
					}

					lineNum++;	
					textArea.append(lineStr);
					rbw.write(lineStr);
				}
				//while循环输出多出的行数
				while ((cbrStr = cbr.readLine()) != null)
				{
					lineStr = "---true.txt-----:   " + lineNum + "\n";
					lineNum++;	
					textArea.append(lineStr);
					rbw.write(lineStr);
				}
				while((brStr = br.readLine()) != null )
				{
					lineStr = "---out.txt------:   " + lineNum + "\n";
					lineNum++;	
					textArea.append(lineStr);
					rbw.write(lineStr);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				br.close();
				cbr.close();
				rbw.close();
				long endTime = System.currentTimeMillis();
				textArea.append((endTime - startTime) / 1000D + "s");
			}

		} catch (IOException e) {
			e.printStackTrace();
		} 





	}  
	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
		//回车
		//当选中时把按钮设置为默认按钮
		textArea.append("确认 " + "\n");
		getRootPane().setDefaultButton(jBt3Start);
		long startTime = System.currentTimeMillis();

		USER = textUser.getText();
		PASS = textPassword.getText();

		Connection conn = null;
		Statement stmt = null;
		try {


			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(DB_URL, USER, PASS);

			stmt = conn.createStatement();	
			BufferedReader  br = new BufferedReader(new FileReader(DATA_SQL));
			BufferedWriter  wbw = new BufferedWriter(new FileWriter(FILE_PATH));

			String str = null;
			textArea.append("连接成功 " + "\n");

			try {
				String sql= null;
				while((sql = br.readLine()) != null ) 
				{
					textArea.append(sql + "\n");
					conn.createStatement().executeUpdate(sql);
				}
				String sqlselect = "select * from T_STUDENT";
				conn.createStatement().executeQuery (sqlselect);
				textArea.append(sqlselect + "\n");
				PreparedStatement pstmt;

				pstmt = (PreparedStatement)conn.prepareStatement(sqlselect);
				ResultSet rs = pstmt.executeQuery();
				int col = rs.getMetaData().getColumnCount();
				while (rs.next()) {
					for (int i = 1; i <= col; i++) {
						str = (rs.getString(i)+ "\t");
						if ((i == 3) && (rs.getString(i).length() < 8)) {
							textArea.append("\t");
							str = str + "\n";
						}
						textArea.append(str);
						wbw.write(str);
					}
				}	
				pstmt.close();
			} catch (SQLException se) {
				textArea.append("数据库名或密码错误!" + "\n");
				return;
			} catch (Exception e) {  
				e.printStackTrace();
			} finally {

				br.close();
				wbw.close();
				conn.close();
				long endTime = System.currentTimeMillis();
				textArea.append((endTime - startTime) / 1000D + "s");
			}


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





	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {

		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new NewJFrame().setVisible(true);
			}
		});

	}

	// Variables declaration - do not modify                     
	private javax.swing.JButton jBtUser;
	private javax.swing.JButton jBtPassword;
	private javax.swing.JButton jBt3Start;
	private java.awt.Label labUser;
	private java.awt.Label labPassword;
	private java.awt.Label labStart;
	private static java.awt.TextArea textArea;
	private java.awt.TextField textUser;
	private java.awt.TextField textPassword;
	// End of variables declaration     

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值