private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Class.forName("com.mysql.jdbc.Driver");
// establish connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/grade", "root", "");
Statement statement = con.createStatement();
statement.executeUpdate("INSERT INTO marks(id,name,quiz,a1,a2,exam,marks,grade) VALUES ('" + id.getText() + "','" + name.getText() + "','" + quiz.getText() + "','"+a1.getText()+"','"+a2.getText()+"','"+"','"+exam.getText()+"','"+marks.getText()+"','"+grade.getText()+"')");
JOptionPane.showMessageDialog(null, "Record inserted...");
statement.close();
con.close();
} catch (SQLException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
}
您的错误消息表示您的Statement
有问题。我建议改用PreparedStatement
和局部变量,这些局部变量将允许您检查传递给[SQL] INSERT
语句的值。
下面的代码只是我建议您使用的JDBC代码。请注意,不再需要使用Class.forName()
加载JDBC驱动程序。我的代码还使用try-with-resources,这是关闭Connection
和PreparedStatement
之类的首选方式。
String sql = "INSERT INTO marks (id," +
"name," +
"quiz," +
"a1," +
"a2," +
"exam," +
"marks," +
"grade) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
String theId = id.getText();
String theName = name.getText();
String theQuiz = quiz.getText();
String theA1 = a1.getText();
String theA2 = a2.getText();
String theExam = exam.getText();
String theMarks = marks.getText();
String theGrade = grade.getText();
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/grade", "root", "");
PreparedStatement statement = con.prepareStatement(sql)) {
statement.setString(1, theId);
statement.setString(2, theName);
statement.setString(3, theQuiz);
statement.setString(4, theA1);
statement.setString(5, theA2);
statement.setString(6, theExam);
statement.setString(7, theMarks);
statement.setString(8, theGrade);
statement.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
由于您没有发布数据库表marks
的结构,所以我不知道表列的数据类型,因此方法setString()
可能不是最合适的。
您可以编辑您的问题并添加表格结构,我将相应地编辑我的答案。