mysql 使用Java我可以创建一个表,但它不能在数据库中记录

xxls0lw8  于 2023-01-29  发布在  Mysql
关注(0)|答案(1)|浏览(114)

我的知识是不是很好的Java,但每天我都试图改进他们。我做了一个小的图形用户界面的一个部门在工作中。它应该创建一个新的表格在数据库中与目前的人在特定的日期。点击按钮后,它应该生成一个excel文件与所有的记录从数据库(但它仍然是在计划XD)
我遇到了一个问题,我的代码在DB中创建了一个表,名字是我想要的。但是它没有在表中做任何记录。在一些输入之后,表仍然是空的。
下面是我代码:(演示文稿. 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);
            }
        });
    }
}

(SQL访问. 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();
    }
}

请不要对我太苛刻,我还在学习
先谢了。
我的代码在DB中创建了一个表,名字是我想要的。但是它没有在表中做任何记录。在一些输入之后,表仍然是空的。

cuxqih21

cuxqih211#

这可能是因为您确实将“autoCommit”设置为false,但从未提交或刷新您的insert语句。尝试在insert语句之后显式提交/刷新,您可能会做得很好。
编辑:创建了表但未执行插入的原因:DDL总是立即执行,而DML要等到事务提交后才执行。

相关问题