简体   繁体   English

使用Java(JDBC)使用单独的类与MySql进行通信

[英]Communicating with MySql using Java (JDBC) using separate classes

I have done a lot of testing with example code online, and have got things to work when it comes to reading from, and adding fields to a MySql database. 我已经使用示例代码在线进行了大量测试,并且在读取数据以及向MySql数据库添加字段时有很多工作要做。

As I have been progressing along, I am now trying to implement it all to a more advanced setup – using multiple files, building my way up towards a MVC structure… (at least a brave attempt!) 在不断前进的过程中,我现在正在尝试将其全部实施为更高级的设置-使用多个文件,逐步建立MVC结构……(至少是一次很勇敢的尝试!)

I have come to a point, where I can't really see why it doesn't work… getting blind here! 我到了一个地步,在这里我真的看不到为什么它不起作用……在这里瞎了! :/ :/

Please see the attached code. 请参阅随附的代码。 Tried to strip it down to the actual problem to explain it as best as I can; 试图将其分解为实际问题,以尽我所能解释。 (sorry for all the GUI code. – I'll blame the WindowBilder plug-in!) (对不起所有的GUI代码。–我会怪WindowBilder插件!)

I have a button in my "NewContact.java" class, that collects the content (user input) of the textfields, and adding it to the String query = "INSERT INTO contact….” 我的“ NewContact.java”类中有一个按钮,该按钮收集文本字段的内容(用户输入),并将其添加到String query =“ INSERT INTO contact ...”。

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();

            }
        }

});

...so to the question : -Does this line of code ...这样的问题:-这行代码是否

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

send the query to the database online? 在线将查询发送到数据库? This is where it fails: 这是失败的地方:

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

-What am I missing here? 我在这里想念什么? Why do I end up in the catch Exeption...(?) I think I am missing some code to send the query to my database. 为什么我最终遇到了Exeption ...(?),我想缺少一些将查询发送到数据库的代码。 But I am not sure what and where... 但是我不确定什么地方

Here are my files: 这是我的文件:

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: 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 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);

    }
}

I have been using this website a lot for my research. 我一直在使用这个网站进行研究。 I have also checked out this article , this article , ( and this article ) but I still can't get it to work.... Please help! 我还检查了这篇文章这篇文章和这篇文章 ),但是我仍然无法使它工作。...请帮助!

I think the method "mysqlitem.runQuerytoDB();" 我认为方法“ mysqlitem.runQuerytoDB();” closes your connection in finally clause. 在finally子句中关闭您的连接。 Afterwards this connection cannot be used for querying. 此后,该连接不能用于查询。 Your DBConnect class should abstract connecting to db , querying, closing connection operations separately. 您的DBConnect类应该抽象化连接到db,查询,分别关闭连接操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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