读取文本文件内容并将其插入到mysql数据库中

时间:2014-11-11 23:32:03

标签: java sql

美好的一天。我有以下代码,我正在努力工作。我必须阅读文本文件的内容,其中包含问题并将其保存到数据库测试系统。

我面临的主要问题是它没有插入数据库中。而且我不确定它是否正在阅读文本文件。

任何帮助都会受到赞赏

JFrame和主要

public class StudentTestSystems {

    public static void main(String[] args) {

        try {

            Lecturer panel = new Lecturer();

            panel.setVisible(true);
            panel.setLocationRelativeTo(null);
            panel.setResizable(false);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

讲师班

public class Lecturer extends JFrame implements ActionListener {

    Font font = null;
    private JTextField fileField;
    private JButton uploadBtn;
    private JLabel message;
    private JPanel panel;

    public Lecturer() {
        super("LECTURE MENU");

        this.setSize(500, 270);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        font = new Font("Times New Roman", Font.BOLD, 14);

        panel = new JPanel();
        panel.setLayout(null);
        panel.setOpaque(true);
        fileField = new JTextField();
        fileField.setFont(font);
        fileField.setBounds(130, 110, 200, 25);

        Font font2 = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 12);
        message = new JLabel("Type in the file name with it's extension. eg: File.txt");
        message.setFont(font2);
        message.setBounds(130, 140, 280, 25);
        message.setOpaque(true);

        uploadBtn = new JButton("UPLOAD");
        uploadBtn.setFont(font);
        uploadBtn.setBounds(340, 110, 95, 21);

        panel.add(fileField);
        panel.add(uploadBtn);
        panel.add(message);

        add(panel);

    /////// register event
        uploadBtn.addActionListener(this);
        exit.addActionListener(this);

    }

    public void actionPerformed(ActionEvent ev) {
        String file = fileField.getText();

        SetGetQuestionFileName setGet = new SetGetQuestionFileName(file);

        FileInputStream fis = null;
        PreparedStatement preparedStmt = null;

        try {
            String myUrl = "jdbc:mysql://localhost:3306/testsystem";

            Connection conn = DriverManager.getConnection(myUrl, "root", "cput");

            if (ev.getActionCommand().equals("UPLOAD")) {
                File filePathString = new File(file);

                fis = new FileInputStream(filePathString);

                if (fileField.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "File field can't be empty. Try again", "ERROR", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    if (filePathString.exists() && filePathString.isFile()) {

                        try {
                            // the mysql insert statement
                            String query = " insert into users (category_questions, questions, quest_opt_a, , quest_opt_b, , quest_opt_c,  quest_opt_d, correct_option_answer )"
                                    + " values (?, ?, ?, ?, ?)";

                            // create the mysql insert preparedstatement
                            preparedStmt = conn.prepareStatement(query);
                            preparedStmt.setString(1, "JDBC");
                            preparedStmt.setString(2, fileField.getText());
                            preparedStmt.setAsciiStream(3, fis, (int) filePathString.length());
                            //preparedStmt.setString   (3, "a");
                            preparedStmt.setString(4, "b");
                            preparedStmt.setString(5, "c");
                            preparedStmt.setString(6, "d");
                            preparedStmt.setString(7, "a");

                            preparedStmt.executeUpdate();

                            // execute the preparedstatement
                            preparedStmt.executeUpdate();
                            //  myfile.closing();
                            conn.close();

                            JOptionPane.showMessageDialog(null, "File successfuly uploaded", "INFORMATION", JOptionPane.INFORMATION_MESSAGE);
                            fileField.setText("");
                        } catch (Exception ex) {
                        } finally {
                            preparedStmt.close();
                            fis.close();
                            conn.close();
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "File coudn't be found. Do check file name.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        } catch (Exception ex) {
        }

        if (ev.getActionCommand().equals("LOGOUT")) {
            System.exit(0);
        }
    }
}

SetQuestionFileName class

public class SetGetQuestionFileName {

    String myfile;

    public SetGetQuestionFileName(String file) {
        setFileName(file);
    }

    public void setFileName(String file) {
        myfile = file;
    }

    public String getFileName() {
        return myfile;
    }
}

1 个答案:

答案 0 :(得分:1)

这是一个关于如何读取文件的简短版本(逐行):

Scanner scanner = new Scanner(filename);
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
}

这是您的查询。那里有太多,或空列名称以及列数和?不匹配:

String query = " insert into users (
                        category_questions, 
                        questions, 
                        quest_opt_a, 
                        ,              // empty column name
                        quest_opt_b, 
                        ,              // empty column name
                        quest_opt_c,  
                        quest_opt_d, 
                        correct_option_answer    
                )" + " values (?, ?, ?, ?, ?)"; // you have 7 columns (without the empty ones) but only 5 ?

这是您的查询的重新格式化版本。我刚删除了,并添加了2 ?

String query = "INSERT INTO users (
                        category_questions, 
                        questions, 
                        quest_opt_a,
                        quest_opt_b, 
                        quest_opt_c,  
                        quest_opt_d, 
                        correct_option_answer 
                 ) VALUES (?, ?, ?, ?, ?, ?, ?)"; 

现在我正在尝试了解您要添加的值:

preparedStmt.setString(1, "JDBC");    // so JDBC is your category ?
preparedStmt.setString(2, fileField.getText()); // I guess this should be the question?
preparedStmt.setString(3, "a");       // according to the column names this needs to be option A
preparedStmt.setString(4, "b");       // option b
preparedStmt.setString(5, "c");       // option c
preparedStmt.setString(6, "d");       // option d
preparedStmt.setString(7, "a");       // answer

到目前为止一切顺利。如果我正确解释列名称,这应该工作。现在唯一剩下的就是获取第2列的真正问题文本(来自文件)。

我不知道你的文件是怎么样的,所以我可以给你一个例子:

textfile in this format:  question? answerA, answerB, answerC, answerD, correctAnswer
-------------------------------------------------------------------------------------
What is the color of the sun? pink, blue, yellow, green, c
What is the smallest number? 3, 1, 7, 200, b

这就是你可以一次读取文件并填充数据库的方法:

// prepare the query
String query = "INSERT INTO users (
                        category_questions, 
                        questions, 
                        quest_opt_a,
                        quest_opt_b, 
                        quest_opt_c,  
                        quest_opt_d, 
                        correct_option_answer 
                 ) VALUES (?, ?, ?, ?, ?, ?, ?)"; 

// load the file
Scanner scanner = new Scanner(filename);
// read the file line by line
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();

    String[] questionAnswer = line.split("?")[ // line.split["?"] will split the line into two strings, right at the ? and put those two strings into an array. 
    String question = questionAnswer[0]  // so [0] will access the first element in that array - the question 
    String[] answers = questionAnswer[1].split(","); // now we split the string after the ? into many strings divided by comma

    preparedStmt.setString(1, "JDBC");   
    preparedStmt.setString(2, question);  
    preparedStmt.setString(3, answers[0]);     
    preparedStmt.setString(4, answers[1]);      
    preparedStmt.setString(5, answers[2]);       
    preparedStmt.setString(6, answers[3]);      
    preparedStmt.setString(7, answers[4]);      

    preparedStmt.executeUpdate();
}

有很多方法可以从文本文件中读取该行并将其拆分为问题和答案。这取决于您从中读取的文件及其格式。

FIY:你最后两次执行preparedStmt.executeUpdate();:)