我试图实施薪资系统并遇到一些问题。该程序需要能够从mysql db检索数据到jtextfield。
当我尝试搜索时,我得到并且错误地说" com.mysql.jdbc.exception.jdbc4.MySQLSyntaxErrorException。您的SQL systax中有错误;查看与您的MySQL服务器版本对应的手册,以便在#"'附近使用正确的语法。在第1行"
package AppPackage;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AllowanceGUI extends javax.swing.JFrame {
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
public AllowanceGUI() {
initComponents();
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
conn=MySQLConnect.ConnectDb();
}
private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "SELECT EmployeeID,FirstName,LastName,Designation,BasicSalary FROM EmployeeInfo WHERE EmployeeID =?";
pst=conn.prepareStatement(sql);
pst.setString(1,EmployeeIDSearchField.getText());
rs = pst.executeQuery(sql);
while(rs.next()) {
EmployeeIDField.setText(rs.getString("EmployeeID"));
FirstNameField.setText(rs.getString("FirstName"));
LasNameField.setText(rs.getString("LastName"));
DesignationField.setText(rs.getString("Designation"));
BasicSalaryField.setText(rs.getString("BasicSalary"));
}
} catch (SQLException e ) {
JOptionPane.showMessageDialog(null, e);
}}
我的数据库连接如下;
包AppPackage;
import java.sql.*;
import javax.swing.*;
public class MySQLConnect {
Connection conn = null;
public static Connection ConnectDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://Localhost/easypay","root","");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
任何人都可以帮我解释一下这段代码吗?
答案 0 :(得分:5)
pst=conn.prepareStatement(sql);// Prepare this sql query for me
pst.setString(1,EmployeeIDSearchField.getText());// Attach this value as first parameter
rs = pst.executeQuery(sql);// IGNORE EVERYTHING, Execute this query
你应该在第三行做pst.executeQuery();
。
修改强>
完全阅读了这是一个选择的事实。你应该在没有字符串查询的情况下执行executeQuery。 附:为了更快的速度,使用列索引(整数)而不是rs.next()循环中的列名。
答案 1 :(得分:5)
终于找到了错误。
private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "SELECT EmployeeID,FirstName,LastName,Designation,BasicSalary FROM EmployeeInfo WHERE EmployeeID =?";
pst=conn.prepareStatement(sql);
pst.setString(1,EmployeeIDSearchField.getText());
rs = pst.executeQuery();
if(rs.next()) {
String ID = rs.getString("EmployeeID");
EmployeeIDField.setText(ID);
String FN = rs.getString("FirstName");
FirstNameField.setText(FN);
String LN = rs.getString("LastName");
LasNameField.setText(LN);
String Des = rs.getString("Designation");
DesignationField.setText(Des);
String BS = rs.getString("BasicSalary");
BasicSalaryField.setText(BS);
}
} catch (SQLException e ) {
JOptionPane.showMessageDialog(null, e);
}
}