【发布时间】:2015-01-11 14:14:47
【问题描述】:
美好的一天。我想使用 pepraredStatement 插入数据库。但是,每当我添加数据库部分(连接和 pepraredStatement)时,“上传”按钮就会无响应。但是当我删除与数据库相关的任何内容时,我所有的按钮都在工作。你可以在这里找到代码http://pastebin.com/euKdWhr2。
我将非常感谢任何帮助或建议。可能我在数据库部分遗漏了一些东西。
public void actionPerformed(ActionEvent ev)
{
String file = fileField.getText();
SetGetQuestionFileName pattern = new SetGetQuestionFileName(file);
ConnectToDatabase database = new ConnectToDatabase();
try
{
///////// check whether textfile is empty or not
if( ev.getActionCommand().equals("UPLOAD"))
{
if(fileField.getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"File field can not be empty!!! Please try again.","ALERT", JOptionPane.ERROR_MESSAGE);
}
else
{
File fi = new File(fileField.getText());
//////////////// perform upload
try
{
String sql = "INSERT INTO testsystem.questionnaire (category_questions, questions, correct_answer)" + "VALUES (?, ?, ?)";
PreparedStatement st = null;
Connection dbconnection = database.getConnection();
st = dbconnection.prepareStatement(sql);
if(fi.getAbsoluteFile().exists())
{
List<String> lines = Files.readAllLines(Paths.get(fileField.getText()), Charset.defaultCharset());
for (int i = 0; i < lines.size(); i+=10)
{
String category = lines.get(i);
System.out.println(category);
String question = lines.get(i+1);
System.out.println(question);
String answers =
lines.get(i+2)+System.lineSeparator()
+lines.get(i+3)+System.lineSeparator()
+lines.get(i+4)+System.lineSeparator()
+lines.get(i+5);
System.out.println(answers);
String correct = lines.get(i+7);
System.out.println("correct answer is: "+correct);
System.out.println("----------------");
st.setString(1, category);
st.setString(2, answers);
st.setString(3, correct);
st.executeUpdate();
}
JOptionPane.showMessageDialog(null,"File has been successfully uploaded in the database.","NOTIFCATION",JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null,"File could not be found. Please try again","ALERT",JOptionPane.ERROR_MESSAGE);
}
catch(SQLException ex)
{
}
catch(Exception ex)
{
}
【问题讨论】:
-
永远不要在不处理异常的情况下捕获异常。或者你重新抛出它们,或者至少记录它们。此外,不要在启动侦听器的线程中执行重要的逻辑;如果你的逻辑可能不是即时的,那么你应该启动一个不同的线程来处理它。
-
Swing 是单线程的,任何长时间运行或阻塞的代码都会阻止 UI 更新,请参阅 Concurrency in Swing 和 Worker Threads and SwingWorker
-
为什么会有
catch(SQLException e) {}和catch(Exception e) {}?如果出了问题,您不想知道出了什么问题吗?
标签: java mysql swing jdbc swingworker