I am trying to create a program that allows users to insert data into a table. Here is my code:
我正在尝试创建一个允许用户将数据插入表中的程序。这是我的代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class DbMethods {
static String query="";
static Statement statement = null;
public static void main(String[] args) throws SQLException, ClassNotFoundException{
// throws SQLException, ClassNotFoundException {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/javabook","root","");
System.out.println("Database connected");
// Create a statement
statement = (Statement)connection.createStatement();
}
public static void insert() throws SQLException{
if(!DbInterface.ID.getText().equals("")){
statement.executeUpdate("INSERT INTO personnel(ID, LastName, FirstName, mi, Address, City, State, Telephone)" + "VALUES('" + DbInterface.ID.getText() + "','" + DbInterface.lastName.getText() + "','" + DbInterface.firstName.getText() + "','" + DbInterface.mi.getText() + "','" + DbInterface.address.getText() + "','" + DbInterface.city.getText() + "','" + DbInterface.state.getText() + "','" + DbInterface.tel.getText() + "')");
}
else
JOptionPane.showMessageDialog(DbInterface.contentPane, "The ID cannot be null!", "Invalid info", JOptionPane.WARNING_MESSAGE);
}
}
I also have created another class to keep the textfields in and get the input from the user.I have only added one actionlistener just for the insert button for now.Here is the class:
我还创建了另一个类来保存文本字段并从用户那里获取输入。我只为插入按钮添加了一个actionlistener for now.Here是类:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class DbInterface extends JFrame {
//text_fields
static JPanel contentPane;
static JTextField ID;
static JTextField lastName;
static JTextField firstName;
static JTextField mi;
static JTextField address;
static JTextField city;
static JTextField state;
static JTextField tel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DbInterface frame = new DbInterface();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DbInterface() {
setTitle("Personnel Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 656, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblPersonel = new JLabel("Personnel Information");
lblPersonel.setBounds(12, 0, 126, 16);
panel.add(lblPersonel);
JLabel lblId = new JLabel("ID");
lblId.setBounds(12, 29, 56, 16);
panel.add(lblId);
ID = new JTextField();
ID.setBounds(80, 26, 204, 22);
panel.add(ID);
ID.setColumns(10);
JLabel lblLastName = new JLabel("Last Name");
lblLastName.setBounds(12, 68, 78, 16);
panel.add(lblLastName);
lastName = new JTextField();
lastName.setBounds(79, 65, 171, 22);
panel.add(lastName);
lastName.setColumns(10);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(262, 68, 78, 16);
panel.add(lblFirstName);
firstName = new JTextField();
firstName.setBounds(332, 65, 171, 22);
panel.add(firstName);
firstName.setColumns(10);
JLabel lblMi = new JLabel("mi");
lblMi.setBounds(529, 68, 56, 16);
panel.add(lblMi);
mi = new JTextField();
mi.setBounds(560, 65, 56, 22);
panel.add(mi);
mi.setColumns(10);
JLabel lblAdress = new JLabel("Address");
lblAdress.setBounds(12, 116, 56, 16);
panel.add(lblAdress);
address = new JTextField();
address.setBounds(79, 113, 424, 22);
panel.add(address);
address.setColumns(10);
JLabel lblCity = new JLabel("City");
lblCity.setBounds(12, 158, 56, 16);
panel.add(lblCity);
city = new JTextField();
city.setBounds(79, 155, 216, 22);
panel.add(city);
city.setColumns(10);
JLabel lblState = new JLabel("State");
lblState.setBounds(332, 158, 56, 16);
panel.add(lblState);
state = new JTextField();
state.setBounds(387, 155, 116, 22);
panel.add(state);
state.setColumns(10);
JLabel lblTelephone = new JLabel("Telephone");
lblTelephone.setBounds(12, 204, 78, 16);
panel.add(lblTelephone);
tel = new JTextField();
tel.setBounds(80, 201, 423, 22);
panel.add(tel);
tel.setColumns(10);
JButton btnNewButton = new JButton("View");
btnNewButton.setBounds(80, 289, 97, 25);
panel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Insert");
btnNewButton_1.setBounds(187, 289, 97, 25);
panel.add(btnNewButton_1);
btnNewButton_1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
try {
DbMethods.insert();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
JButton btnNewButton_2 = new JButton("Update");
btnNewButton_2.setBounds(291, 289, 97, 25);
panel.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Clear");
btnNewButton_3.setBounds(400, 289, 97, 25);
panel.add(btnNewButton_3);
}
}
When I run the second class and try to insert a record into database I get the null pointer exception.
当我运行第二个类并尝试将记录插入数据库时,我得到空指针异常。
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at DbMethods.insert(DbMethods.java:45)
at DbInterface$2.actionPerformed(DbInterface.java:162)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
and I don't know why, if anyone could help, that would be great.
我不知道为什么,如果有人能提供帮助,那就太好了。
1 个解决方案
#1
2
If you start the program by calling the main(....)
method in DbInterface
the statement variable in DbMethods
will be null
, if you started it by calling main(...)
in DbMethods
all of the variables in DbInterface
will be null
.
如果通过调用DbInterface中的main(....)方法启动程序,则DbMethods中的语句变量将为null,如果通过在DbMethods中调用main(...)启动它,则DbInterface中的所有变量将为null 。
Also, don't execute database operation on the EDT.
另外,不要在EDT上执行数据库操作。
You can modify the DbMethods
class to something like this:
您可以将DbMethods类修改为以下内容:
public class DbMethods {
public void insert(String f1,String f2 ....){
if(f1.isEmpty()){
JOptionPane.showMessageDialog(DbInterface.contentPane, "The ID cannot be null!", "Invalid info", JOptionPane.WARNING_MESSAGE);
}else{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook","root","");
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO personnel(ID, LastName, FirstName, mi, Address, City, State, Telephone) VALUES('"+f1+"','"+f2+"'"+....+")");
}
}
}
And in the DbInterface
class you can call the insert(...)
method like this:
在DbInterface类中,您可以像这样调用insert(...)方法:
btnNewButton_1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
new Thread(new Runnable(){
public void run(){
new DbMethods().insert(id.getText(), lastName.getText(),....);
}
}).start();
}
});
You should consider using PreparedStatement
instead of Statement
and create only a single connection to the database.
您应该考虑使用PreparedStatement而不是Statement,并且只创建与数据库的单个连接。
#1
2
If you start the program by calling the main(....)
method in DbInterface
the statement variable in DbMethods
will be null
, if you started it by calling main(...)
in DbMethods
all of the variables in DbInterface
will be null
.
如果通过调用DbInterface中的main(....)方法启动程序,则DbMethods中的语句变量将为null,如果通过在DbMethods中调用main(...)启动它,则DbInterface中的所有变量将为null 。
Also, don't execute database operation on the EDT.
另外,不要在EDT上执行数据库操作。
You can modify the DbMethods
class to something like this:
您可以将DbMethods类修改为以下内容:
public class DbMethods {
public void insert(String f1,String f2 ....){
if(f1.isEmpty()){
JOptionPane.showMessageDialog(DbInterface.contentPane, "The ID cannot be null!", "Invalid info", JOptionPane.WARNING_MESSAGE);
}else{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook","root","");
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO personnel(ID, LastName, FirstName, mi, Address, City, State, Telephone) VALUES('"+f1+"','"+f2+"'"+....+")");
}
}
}
And in the DbInterface
class you can call the insert(...)
method like this:
在DbInterface类中,您可以像这样调用insert(...)方法:
btnNewButton_1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
new Thread(new Runnable(){
public void run(){
new DbMethods().insert(id.getText(), lastName.getText(),....);
}
}).start();
}
});
You should consider using PreparedStatement
instead of Statement
and create only a single connection to the database.
您应该考虑使用PreparedStatement而不是Statement,并且只创建与数据库的单个连接。