public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if(action.equals("Reset")){
title.setSelectedIndex(0);
forename.setText(null);
surname.setText(null);
age.setText(null);
contactNo.setText(null);
houseNo.setText(null);
streetName.setText(null);
districtName.setText(null);
cityName.setText(null);
postcode.setText(null);
healthPlan.setSelectedIndex(0);
treatment.setSelectedIndex(0);
}
单击“提交”按钮时,如何使用文本字段中的数据更新sql数据库。到目前为止,我已经编写了这段代码,但是当我点击提交时似乎没有发生任何事情,但是单击它时重置按钮会起作用。
if(action.equals("Submit")){
Connection con = null;
String db="jdbc:mysql://stusql.dcs.shef.ac.uk/team009?user=team009&password=********";
try {
con = DriverManager.getConnection(db);
Statement bil = con.createStatement();
bil.execute("INSERT INTO Patient (ForeName, SurName, DateOfBirth, PhoneNumber, HouseNumber, PostCode) " +
"VALUES (forename.getText(),surname.getText,age.getText,contactNo.getText(),houseNo.getText(),postcode.getText())");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch (SQLException ex) {
ex.printStackTrace();
}
finally {
if (con != null)
try {
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
请任何帮助将不胜感激。
答案 0 :(得分:1)
基本上,您当前的查询String
"INSERT INTO Patient (ForeName, SurName, DateOfBirth, PhoneNumber, HouseNumber, PostCode) " +
"VALUES (forename.getText(),surname.getText,age.getText,contactNo.getText(),houseNo.getText(),postcode.getText())"
字面上要求数据库插入您提供的文本而不是文本字段中的文本,事实上,数据库应该非常适合这一点并且返回Exception
。最好的情况是,它试图找到匹配surname.getText
之类的表格/列值,最糟糕的是它正在寻找名为forename.getText()
的函数
首先看看:
例如......
try (Connection con = DriverManager.getConnection(null)) {
try (PreparedStatement stmt = con.prepareStatement("INSERT INTO Patient (ForeName, SurName, DateOfBirth, PhoneNumber, HouseNumber, PostCode) VALUES (?,?,?,?,?,?)")) {
stmt.setString(1, forename.getText());
stmt.setString(2, surname.getText());
stmt.setString(3, age.getText());
stmt.setString(4, contactNo.getText());
stmt.setString(5, houseNo.getText());
stmt.setString(6, postcode.getText());
// In case you care, you can get the number of rows that were updated...
int rowsUpdated = stmt.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
您可能会发现The try-with-resources Statement有用......
答案 1 :(得分:0)
您没有发送forename
,surname
等的值,而是发送字符串
在java中调用这些值。您需要使用以下代码部分: -
bil.execute("INSERT INTO Patient (ForeName, SurName, DateOfBirth, PhoneNumber, HouseNumber, PostCode) VALUES ("'
+ forename.getText() + "', '"
+ surname.getText() + "', '"
+ age.getText() + "', '"
+ contactNo.getText() + "', '"
+ houseNo.getText() + "', '"
+ postcode.getText() + "')");