简体   繁体   中英

Using Java I can create a table, but it doesnt make record in DB

My knolages is not so good in Java, but every day I try to omprove them. I make a small GUI for one dep at work. It should create a new tabel in DB with present people on specific date. after click the button, it should generate an excel file with all the records from DB (but it is still in plans XD)

I met a problem, that my code creates the table in DB, with name as I want. but it don do any record in Table. after some inputs, the table remains empty.

here is my code: (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);
            }
        });
    }
}

(SQLAccess.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();
    }
}

Please don't judge me too harshly, I'm still learning

Thanks In advance.

that my code creates the table in DB, with name as I want. but it don do any record in Table. after some inputs, the table remains empty.

It might be because you do set the "autoCommit" to false, but never commit or flush your insert statement. Try to commit / flush explicitly after the insert statement and you might be good to go.

Edit: The reason why tables are created but inserts are not happening: DDL will always be executed right away, whilst DML will not until the transaction is committed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM