2014-11-06 59 views
0

我已經使用在線示例代碼進行了大量測試,並且在讀取MySql數據庫和向MySql數據庫添加字段時已經有了一些工作。使用獨立的類使用Java(JDBC)與MySql進行通信

正如我一直在進步一起,我現在想給它的所有執行一個更高級設置 - 使用多個文件,建立我的方式向MVC結構...(至少一個大膽的嘗試!)

我已經到了一個地步,在那裏我不明白爲什麼它不起作用......在這裏失明! :/

請參閱附件代碼。試圖把它解決到實際問題,盡我所能解釋它; (對不起所有的GUI代碼 - 我會責怪WindowBilder插件!)

我在我的「NewContact.java」類中有一個按鈕,它收集文本字段的內容(用戶輸入),以及將它添加到字符串查詢=「INSERT INTO接觸​​...。」

btnAddContact.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 

      textfield_firstname.getText(); 
      textfield_surname.getText(); 

      mysqlitem = new DBConnect(); 
      mysqlitem.runQuerytoDB(); 

      String query = "INSERT INTO contact (`firstname`, `surname`) VALUES ('" + textfield_firstname + "', '" + textfield_surname + "')"; 

      try { 
       mysqlitem.resultSet = mysqlitem.statement.executeQuery(query); 
      } catch (Exception e1) { 
       //this is where it fails!!!! 
       e1.printStackTrace(); 

      } 
     } 

}); 

......這樣的問題: -Does這行代碼

mysqlitem.resultSet = mysqlitem.statement.executeQuery(query); 

發送查詢到數據庫在線?這是它失敗的地方:

 try { 
      mysqlitem.resultSet = mysqlitem.statement.executeQuery(query); 
     } catch (Exception e1) { 
      //this is where it fails!!!! 
      e1.printStackTrace(); 

- 我在這裏錯過了什麼?爲什麼我最終在catch Exeption ...(?) 我想我錯過了一些代碼發送查詢到我的數據庫。但是我不知道什麼,在哪裏......

這裏是我的文件:

GUI.java

package view; 

import java.awt.CardLayout; 

public class GUI extends JFrame { 

private static final long serialVersionUID = -8116151922074331976L; 

private JDesktopPane desktopPane; 

private JPanel contentPane; 

private NewContact newContact; 

public static void main(String[] args) { 
    try { 
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
    } catch (Throwable e) { 
     e.printStackTrace(); 
    } 

    new DBConnect(); 
    new NewContact(); 

    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       GUI frame = new GUI(); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

public GUI() { 
    initComponents(); 
    createEvents(); 
    if (newContact == null || newContact.isClosed()) { 
     newContact = new NewContact(); 
     desktopPane.add(newContact); 
     newContact.show(); 
    } 

} 

private void initComponents() { 

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    setBounds(50, 50, 435, 430); 

    contentPane = new JPanel(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    setContentPane(contentPane); 

    desktopPane = new JDesktopPane(); 
    desktopPane.setBackground(SystemColor.inactiveCaption); 
    GroupLayout gl_contentPane = new GroupLayout(contentPane); 
    gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING).addComponent(desktopPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)); 
    gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane.createSequentialGroup().addGap(43).addComponent(desktopPane, GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE))); 
    desktopPane.setLayout(new CardLayout(0, 0)); 

    DefaultTableCellRenderer leftRenderer = new DefaultTableCellRenderer(); 
    leftRenderer.setHorizontalAlignment(SwingConstants.LEFT); 
    DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(); 
    rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT); 
    DefaultTableCellRenderer middleRenderer = new DefaultTableCellRenderer(); 
    middleRenderer.setHorizontalAlignment(SwingConstants.CENTER); 

    contentPane.setLayout(gl_contentPane); 
} 

private void createEvents() { 

} 
} 

DBConnect.java:

package view; 

import java.sql.*; 

import javax.swing.JOptionPane; 

public class DBConnect { 

// JDBC driver name and database URL 
protected String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
protected String DB_URL = "jdbc:mysql://mysql99.servetheworld.net:3306/my_javaapp"; 

// Database credentials 
protected String USER = "my_username"; 
protected String PASS = "...some password"; 

// SQL string builder 
protected Connection connection = null; 
protected Statement statement = null; 
protected ResultSet resultSet; 

public DBConnect() { 

} 

public void runQuerytoDB() { 

    try { 

     Class.forName(JDBC_DRIVER).newInstance(); 
     connection = DriverManager.getConnection(DB_URL, USER, PASS); 
     System.out.println("Connected to the db"); 
     statement = connection.createStatement(); 

    } catch (Exception ex) { 
     System.out.println("Error connecting to db: " + ex); 
    } finally { 
     try { 
      if (statement != null) 
       connection.close(); 
     } catch (SQLException se) { 
     } 
     try { 
      if (connection != null) 
       connection.close(); 
     } catch (SQLException se) { 
      se.printStackTrace(); 
     } 
     try { 
      if (resultSet != null) 
       connection.close(); 
     } catch (SQLException se) { 
     } 
    } 
} 
} 

NewContact.java

package view; 

import java.beans.PropertyVetoException; 

public class NewContact extends JInternalFrame { 

private static final long serialVersionUID = -4310258665254170668L; 

protected static final char[][] ArrayList = null; 

private JTextField textfield_firstname; 
private JTextField textfield_surname; 

DBConnect mysqlitem; 

public NewContact() { 

    setResizable(true); 


    setTitle("New Contact"); 
    setClosable(true); 
    try { 
     setClosed(true); 
    } catch (PropertyVetoException e) { 
     e.printStackTrace(); 
    } 
    setBounds(0, 0, 219, 270); 

    JPanel panelData = new JPanel(); 
    panelData.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Details", TitledBorder.LEADING, TitledBorder.TOP, null, null)); 

    JPanel panelButtons = new JPanel(); 
    GroupLayout groupLayout = new GroupLayout(getContentPane()); 
    groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.TRAILING).addGroup(
      Alignment.LEADING, 
      groupLayout.createSequentialGroup().addContainerGap() 
        .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false).addComponent(panelButtons, Alignment.LEADING, 0, 0, Short.MAX_VALUE).addComponent(panelData, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 177, Short.MAX_VALUE)).addContainerGap(141, Short.MAX_VALUE))); 
    groupLayout 
      .setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(
        groupLayout.createSequentialGroup().addContainerGap().addComponent(panelData, GroupLayout.PREFERRED_SIZE, 137, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(panelButtons, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE) 
          .addGap(34))); 

    JButton btnAddContact = new JButton("Add contact to DB"); 

    btnAddContact.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 

      textfield_firstname.getText(); 

      textfield_surname.getText(); 

      mysqlitem = new DBConnect(); 

      mysqlitem.runQuerytoDB(); 
      String query = "INSERT INTO contact (`firstname`, `surname`) VALUES ('" + textfield_firstname + "', '" + textfield_surname + "')"; 

      try { 

       mysqlitem.resultSet = mysqlitem.statement.executeQuery(query); 
      } catch (Exception e1) { 
       e1.printStackTrace(); 

      } 
     } 

    }); 

    GroupLayout gl_panelButtons = new GroupLayout(panelButtons); 
    gl_panelButtons.setHorizontalGroup(gl_panelButtons.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING, 
      gl_panelButtons.createSequentialGroup().addContainerGap().addComponent(btnAddContact, GroupLayout.PREFERRED_SIZE, 143, GroupLayout.PREFERRED_SIZE).addContainerGap(155, Short.MAX_VALUE))); 
    gl_panelButtons.setVerticalGroup(gl_panelButtons.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING, gl_panelButtons.createSequentialGroup().addContainerGap().addComponent(btnAddContact).addContainerGap(30, Short.MAX_VALUE))); 
    panelButtons.setLayout(gl_panelButtons); 

    JLabel lblFornavn = new JLabel("Firstname:"); 

    textfield_firstname = new JTextField(); 
    textfield_firstname.setColumns(10); 

    JLabel lblSurName = new JLabel("Last name:"); 

    textfield_surname = new JTextField(); 
    textfield_surname.setColumns(10); 
    GroupLayout gl_panelData = new GroupLayout(panelData); 
    gl_panelData 
      .setHorizontalGroup(gl_panelData.createParallelGroup(Alignment.LEADING).addGroup(
        gl_panelData 
          .createSequentialGroup() 
          .addContainerGap() 
          .addGroup(
            gl_panelData 
              .createParallelGroup(Alignment.TRAILING) 
              .addGroup(gl_panelData.createSequentialGroup().addComponent(lblFornavn).addGap(201)) 
              .addGroup(gl_panelData.createSequentialGroup().addComponent(lblSurName).addContainerGap(233, Short.MAX_VALUE)) 
              .addGroup(
                Alignment.LEADING, 
                gl_panelData.createSequentialGroup() 
                  .addGroup(gl_panelData.createParallelGroup(Alignment.TRAILING, false).addComponent(textfield_surname, Alignment.LEADING).addComponent(textfield_firstname, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)) 
                  .addContainerGap())))); 
    gl_panelData.setVerticalGroup(gl_panelData.createParallelGroup(Alignment.LEADING).addGroup(
      gl_panelData.createSequentialGroup().addContainerGap().addComponent(lblFornavn).addPreferredGap(ComponentPlacement.RELATED).addComponent(textfield_firstname, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) 
        .addPreferredGap(ComponentPlacement.UNRELATED).addComponent(lblSurName).addPreferredGap(ComponentPlacement.RELATED).addComponent(textfield_surname, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(64))); 
    panelData.setLayout(gl_panelData); 
    getContentPane().setLayout(groupLayout); 

    } 
} 

我有我的研究一直在使用this website。我也檢查了this articlethis article,(and this article),但我仍然無法得到它的工作....請幫助!

回答

0

我覺得方法「mysqlitem.runQuerytoDB();」在finally子句中關閉您的連接。之後,此連接不能用於查詢。您的DBConnect類應該將連接抽象爲db,查詢,分開關閉連接操作。

+0

感謝您抽出寶貴時間回覆。你的意思是這樣的:http://www.caveofprogramming.com/frontpage/youtube/java-video/java-for-complete-beginners-video-part-38-abstract-classes/我還在這個過程中學習Java,所以我不是100%熟悉所有的術語。 – CustomCase 2014-11-07 11:01:24

+0

http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm這是更好的例子開始,但你應該嘗試更多的代碼 – musti77 2014-11-10 12:43:16

+0

我已經使用http://www.tutorialspoint.com/jdbc/ jdbc-sample-code.htm網站已經爲我的研究做了很多工作。問題是,這隻有一個文件中的代碼...我試圖分開它以獲得更好的結構。 (MVC)我正準備按照你的說法嘗試; 「抽象連接到數據庫,查詢,分開關閉連接操作。」 :) – CustomCase 2014-11-10 12:45:42

相關問題