如何解决MySQLSyntaxErrorException

时间:2014-06-10 08:24:08

标签: mysql sql swing jcombobox

在我的项目中,我做了一些代码来搜索数据库表中的员工姓名并将其加载到jcombobox中。

表名employee

列名称empid(Primarykey), emp_name, position

通常我会像这样编码我的搜索查询。

public void EmployeeName1(JComboBox comboName) {
    Vector v = new Vector();
    try {
        ResultSet rs = db.getData("select emp_name from employee");
        v.add("--SELECT--");
        while (rs.next()) {
            v.add(rs.getString("emp_name"));
            comboName.setModel(new DefaultComboBoxModel(v));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

它运作良好。

但是现在我对这段代码做了一些不同的事情。

public void EmployeeName1(JComboBox comboName) {
    Vector v = new Vector();
    try {
        String columnName = "emp_name";
        String tableName = "employee";
        ResultSet rs = db.getData("select columnName from tableName");
        v.add("--SELECT--");
        while (rs.next()) {
            v.add(rs.getString(columnName));
            comboName.setModel(new DefaultComboBoxModel(v));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

但是当我运行此代码时,我遇到了这个错误。

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'textile.tablename' doesn't exist

这是我的db类代码:

package Model;

//import static Model.JDBC.con;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;

public class JDBC {

    static String driver = "com.mysql.jdbc.Driver";
    static String url = "jdbc:mysql://localhost/textile";
    static Connection con;
    static boolean b;

    public static void setCon() {
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, "root", "access456");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }

    public static Connection getCon() throws Exception {
        if (con == null) {
            setCon();
        }
        return con;
    }

    public static boolean putData(String sql) {
        try {
            PreparedStatement state = getCon().prepareStatement(sql);
            state.executeUpdate();
            b = true;
        } catch (Exception ex) {
            b = false;
            JOptionPane.showMessageDialog(null, ex);
        }
        return b;
    }

    public static ResultSet getData(String sql) throws Exception {
        Statement state = JDBC.getCon().createStatement();
        ResultSet rset = state.executeQuery(sql);
        return rset;
    }
}

2 个答案:

答案 0 :(得分:0)

在我看来,就像你在两个代码片段之间保持一致。我唯一能看到你应该改变的是:

ResultSet rs = db.getData("select columnName from tableName");

ResultSet rs = db.getData("select " + columnName + " from " + tableName);

答案 1 :(得分:0)

将columnname和tablename添加为变量并更改:

ResultSet rs = db.getData("select columnName from tableName");

ResultSet rs = db.getData("select "+columnName+" from "+tableName);