我试图将数据插入到我的SQL表中。我有一个Jframe:
表单的目的是将写在这些文本字段上的内容输入到数据库中。 我的问题是,当我按发送请求时,没有任何反应..我错过了什么吗?
这是发送请求按钮的代码:
private void SendRequestActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/database","my-user","my-pass");
Statement stmt = con.createStatement();
//execute commands that collects
//the text/items from the fields and converts them to strings
String MedRole = ofMedRoleComboBox.getSelectedItem().toString();
String PtID = ofPatientIDField.getText();
String Date = ofDateField.getText();
String Time = ofTimeField.getText();
String Purpose = ofPurposeComboBox.getSelectedItem().toString();
// sql query
String insertOrdersDB = "INSERT INTO Orders ('PatientID','MedicalRole','Date','Time','Purpose') VALUES ("+MedRole+","+PtID+","+Date+","+Time+","+Purpose+")";
// executing sql query
stmt.executeUpdate(insertOrdersDB);
}
catch (Throwable e) {
e.printStackTrace();
}
}
在 e.printStackTrace(); 中:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the
right syntax to use near ''PatientID','MedicalRole','Date','Time','Purpose') VALUES (Nurse,7,2016-04-13,12' at line 1
我认为这是日期语法,它与SQL不同。所以我改变它以匹配SQL表格式。但仍然有同样的错误。
现在我认为关于时间?
答案 0 :(得分:0)
好的,所以我跟进了你的一些评论和反馈。对此感激不尽。我还在学习Java,我知道我还有很长的路要走。
但无论如何,多亏了你的指导,我设法让我的表格起作用。
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/database","my-user","my-pass");
String sql = "INSERT INTO Orders (PatientID, MedicalRole, Date, Time, Purpose) VALUES (?,?,?,?,?)";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(ofPatientIDField.getText()));
pstmt.setString(2, ofMedRoleComboBox.getSelectedItem().toString());
pstmt.setObject(3, ofDateField.getValue());
pstmt.setObject(4, ofTimeField.getText());
pstmt.setString(5, ofPurposeComboBox.getSelectedItem().toString());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
所以是的,我用之前的尝试替换了它,并且它有效!
感谢您告诉我使用 Prepared Statements :) @MadProgrammer