有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在网上用示例代码做了很多测试,在读取MySql数据库并向其添加字段时,我已经做了很多工作

随着我不断进步,我现在正在尝试将其实现为更高级的设置——使用多个文件,朝着MVC结构发展……(至少是一次勇敢的尝试!)

我已经到了一个地步,我真的不明白为什么它不起作用……在这里失明!:/

请参阅所附代码。试图把它归结为实际问题,尽可能地解释它;(为所有的GUI代码感到抱歉。——我会责怪WindowBilder插件!)

我的“NewContact.java”类中有一个按钮,用于收集文本字段的内容(用户输入),并将其添加到字符串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();

            }
        }

});

。。。所以要回答这个问题: -这行代码

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

是否将查询发送到联机数据库?这就是它失败的地方:

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

-我错过了什么?为什么我最终会被抓。。。(?) 我想我缺少了一些将查询发送到数据库的代码。但我不确定是什么,在哪里

以下是我的文件:

桂。爪哇

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

}
}

数据库连接。爪哇:

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) {
        }
    }
}
}

新联系人。爪哇

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) 个答案