gpt4 book ai didi

mysql - 如何解决 MySQLSyntaxErrorException

转载 作者:行者123 更新时间:2023-11-30 23:00:48 25 4
gpt4 key购买 nike

在我的项目中,我编写了一些代码来从数据库表中搜索员工姓名并将其加载到 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

这是我的数据库类代码:

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;
}
}

最佳答案

在我看来,两个代码片段之间的其他所有内容都保持不变。我唯一能看到你应该改变的是:

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

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

关于mysql - 如何解决 MySQLSyntaxErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com