【发布时间】:2021-07-19 11:52:24
【问题描述】:
我在 mysql 中创建了一个名为 user 的表。然后我创建了一个简单的 j 框架,其中包含一个文本字段和一个按钮。按下按钮后,按钮将在数据库中添加名称。但是在 insertData.InsertData$2.actionPerformed(InsertData.java:86) 处显示错误意味着准备好的语句存在一些问题。我试过没有准备好的陈述,但问题没有解决。 最重要的是我的表有 4 列(名称、ID、电子邮件、电话)
package insertData;
import java.awt.EventQueue;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class InsertData {
private JFrame frame;
private JTextField textField;
Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InsertData window = new InsertData();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public InsertData() {
initialize();
createConnection();
}
/**
* Initialize the contents of the frame.
*/
public void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/shykat_db","root","root"); //Establish connection
System.out.println("sucess");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 25, 174, 44);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Submit\r\n");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String name=textField.getText();
String drop="insert into user values(?) ";
java.sql.PreparedStatement ps= ((java.sql.Connection) connection).prepareStatement(drop);
System.out.println(ps);
ps.setString(1, name);
ps.executeUpdate();
//ResultSet rs = ps.executeQuery();
//System.out.println(rs);
//java.sql.Statement stm=((java.sql.Connection) connection).createStatement();
//String drop="insert into user values(' "+name+" ')";
//stm.execute(drop);
//stm.close();
//int count=ps.executeUpdate();
//System.out.println(count+"-----Data updated");
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(313, 26, 89, 44);
frame.getContentPane().add(btnNewButton);
}
}
【问题讨论】:
-
显示错误什么的?
标签: java mysql prepared-statement