java 如何将数据从java中的文本字段插入sql表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29431513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert data into sql table from a text field in java
提问by CodingAround
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:
我还创建了另一个类来保留文本字段并从用户那里获取输入。我现在只为插入按钮添加了一个动作侦听器。这是类:
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.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.access0(Unknown Source)
at java.awt.EventQueue.run(Unknown Source)
at java.awt.EventQueue.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.run(Unknown Source)
at java.awt.EventQueue.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain.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.
我不知道为什么,如果有人可以提供帮助,那就太好了。
回答by Titus
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
.
如果您通过调用语句中的main(....)
方法启动程序DbInterface
变量 in DbMethods
will null
,如果您通过调用in willmain(...)
中的DbMethods
所有变量启动程序。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
只创建一个到数据库的连接。