Java GUI程序创建MySQL表成功但无法插入数据求助
数据库插入记录失败问题
本人Java能力尚在提升中,为公司某部门开发了一款小型GUI程序,该程序需创建指定日期的数据库表来记录在岗人员信息,后续计划实现点击按钮导出数据库所有记录至Excel的功能(目前仍在规划中)。
目前遇到的问题:程序能够按照预期命名规则创建MySQL数据库表,但无法向表中插入记录,输入数据后表始终为空。
相关代码
PresentaGui.java
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.SQLException; public class PresentaGui extends JFrame { static JLabel lableLog = new JLabel(); public PresentaGui() { super("Test frame"); createGUI(); } public void createGUI() { MySQLAccess mySQLAccess = new MySQLAccess(); Dimension sSize = Toolkit.getDefaultToolkit().getScreenSize(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // начало позиционирования шапки JPanel panel1 = new JPanel(); panel1.setLayout(null); JLabel label1= new JLabel("Op. Number"); JLabel label2= new JLabel("Col. Number"); JLabel label3 = new JLabel("Shift"); JTextField text1 = new JTextField(); JComboBox collectives = new JComboBox(); JComboBox shifts = new JComboBox(); JTextArea textArea =new JTextArea(); textArea.setEditable(false); JButton button = new JButton("Finish"); collectives.addItem("18001"); collectives.addItem("18002"); collectives.addItem("18003"); collectives.addItem("18004"); collectives.addItem("18005"); collectives.addItem("18006"); collectives.addItem("18007"); collectives.addItem("18008"); collectives.addItem("18009"); shifts.addItem("M"); shifts.addItem("T"); shifts.addItem("N"); label1.setBounds(5,5,90,25); label2.setBounds(180, 5, 90,25); label3.setBounds(107, 5, 60, 25); text1.setBounds(5,45,90,25); collectives.setBounds(180,45,90,25); shifts.setBounds(107, 45, 60, 25); lableLog.setBounds(10, 80,265,25); textArea.setBounds(5,120,265, 370); button.setBounds(65,500,155,40); panel1.add(label1); panel1.add(label2); panel1.add(text1); panel1.add(label3); panel1.add(lableLog); panel1.add(shifts); panel1.add(collectives); panel1.add(textArea); panel1.add(button); // Конец позиционирования шапки // начало включения элементов в тело самой формы getContentPane().add(panel1); // Конец включения элементов в тело самой формы setPreferredSize(new Dimension(285,580)); // setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize())); //Берем значение вводимое пользователем text1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // берем значение из инпута String collNumList = collectives.getSelectedItem().toString(); String shiftCode = shifts.getSelectedItem().toString(); String operNumInput = text1.getText(); if(operNumInput.equals("")){ return; } // -------------Create Connection to DB------------- mySQLAccess.mysqlOperations(); // -------------Creation Table in DB ------------- try{ mySQLAccess.createDBTable(collNumList, operNumInput, shiftCode); }catch (SQLException | InterruptedException ex){ System.out.println("Error while adding the record!"); throw new RuntimeException(ex); } // -------------Close Connection with DB ------------- try { mySQLAccess.closeDBConnection(); } catch (SQLException ex) { System.out.println("Error while connection!"); throw new RuntimeException(ex); } //Используем - Например вставляем в другое текстовое поле textArea.append(MySQLAccess.currentTime_db+ " : " +shiftCode+" - "+collNumList+" - "+operNumInput+"\n"); text1.setText(""); } }); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame.setDefaultLookAndFeelDecorated(true); PresentaGui frame = new PresentaGui(); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
MySQLAccess.java
import java.sql.*; import java.text.SimpleDateFormat; import java.util.Date; public class MySQLAccess { private static ResultSet rs = null; private static SimpleDateFormat dtf = new SimpleDateFormat("ddMMyyyy"); private static SimpleDateFormat dft_db = new SimpleDateFormat("dd/MM/yyyy hh:MM:ss"); private static java.util.Date date = new Date(); static String currentTime = dtf.format(date); static String currentTime_db = dft_db.format(date); static Connection connection = null; static PreparedStatement prst = null; String query = ""; public void mysqlOperations() { try { String dbURL = "jdbc:mysql://10.20.193.237:3306/presenta?useSSL=false"; String userName = "artiom"; String passwd = "admin"; Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); try { connection = DriverManager.getConnection(dbURL, userName, passwd); System.out.println("Connection successful"); connection.setAutoCommit(false); connection.commit(); } catch (Exception ex) { System.out.println(ex); } } catch (Exception e) { System.out.println(e); } } public void createTable(Connection con, String collective, String tura) throws SQLException { query = "CREATE TABLE if not exists "+collective+"_"+tura+"_"+currentTime+" (Id int AUTO_INCREMENT, time varchar(255), op_number varchar(255), shift varchar(255), primary key(id));"; prst = con.prepareStatement(query); prst.execute(); } public void makeRecord(Connection con, String collective, String op_number, String tura) throws SQLException { query = "INSERT INTO "+collective+"_"+tura+"_"+currentTime+"(time, op_number, shift ) VALUES ('"+currentTime_db+"', '"+op_number+"', '"+tura+"');"; prst = con.prepareStatement(query); prst.execute(); } public void createDBTable(String collective, String op_number, String tura) throws SQLException, InterruptedException { DatabaseMetaData dbm = connection.getMetaData(); ResultSet tables = dbm.getTables(null, null, ""+collective+"_"+tura+"_"+currentTime+"", null); if (!tables.next()) { createTable(connection, collective, tura); makeRecord(connection, collective, op_number, tura); System.out.println("Created and record!"); } else { createTable(connection, collective, tura); System.out.println("Just Record"); } } public void closeDBConnection() throws SQLException { connection.close(); if(isDBConnected(connection)){ System.out.println("Connection is closed"); }else{ System.out.println("Connection is still opened"); } } public boolean isDBConnected(Connection connection) throws SQLException { return connection != null && connection.isClosed(); } }
恳请各位不要过于严苛,我仍在学习中,提前感谢各位的帮助!
内容的提问来源于stack exchange,提问作者Артём Орёл
相关产品推荐
相关产品推荐

