我已经使用在线示例代码进行了大量测试,并且在读取和向MySql数据库添加字段时已经开始工作了。
随着我的不断进步,我现在正尝试将其全部实现到更高级的设置 - 使用多个文件,向MVC结构迈进......(至少是一次勇敢的尝试!)
我已经到了一个地步,我无法真正理解为什么它不起作用......在这里失明! :/
请参阅附带的代码。试图将其剥离到实际问题,尽可能地解释它; (抱歉所有的GUI代码。 - 我会责怪WindowBilder插件!)
我的" NewContact.java"中有一个按钮。 class,收集文本字段的内容(用户输入),并将其添加到String查询=" 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();
- 我在这里错过了什么?为什么我最终会捕获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 article,this article,(and this article),但我仍然无法让它工作......请帮忙!
答案 0 :(得分:0)
我认为方法" mysqlitem.runQuerytoDB();"在finally子句中关闭你的连接。之后,此连接不能用于查询。您的DBConnect类应该抽象连接到db,查询,单独关闭连接操作。