我在准备好的语句中获取列名而不是值。
这是我的代码:
string q="select ? from EMPLOYEE where salary > ?";
Preparedstatement pst = connectionobject.preparedstatement(q);
pst.setstring(1, "FIRST_NAME");
pst.setint(2, 10000);
当我在JTable
打印结果时,它会在所有行中显示FIRST_NAME
。
答案 0 :(得分:1)
您的preparedStatement必须生成查询:select "FIRST_NAME" from EMPLOYEE where salary > 10000
而不是select FIRST_NAME from EMPLOYEE where salary > 10000
。
因此它返回每行的字符串“FIRST_NAME”。
您可以简单地使用StringBuilder替换第一个'?'由你的column_name。
答案 1 :(得分:1)
这是不可能的,以你的方式来解决你的问题。
更改您的代码:
#require "core"
您应该检查您的列是否存在于您的表中:
String att = "FIRST_NAME";
string q="select " + att + " from EMPLOYEE where salary>?";
Preparedstatement pst=connectionobject.preparedstatement(q);
pst.setint(1,10000);
像这样:
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'
如果列存在,那么您可以这样继续:
public boolean column_exist(String att) {
boolean succes = false;
CreerConnection con = new CreerConnection();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultat = null;
try {
connection = con.getConnection();
statement = connection.prepareStatement("SELECT * \n"
+ "FROM information_schema.COLUMNS "
+ " WHERE"
+ " TABLE_SCHEMA = 'db_name'"
+ " AND TABLE_NAME = 'table_name'"
+ " AND COLUMN_NAME = ?");
statement.setString(1, att);
resultat = statement.executeQuery();
if (resultat.next()) {
succes = true;
}
} catch (SQLException e) {
System.out.println("Exception = " + e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
return succes;
}
在此处了解详情:
MySQL, Check if a column exists in a table with SQL
希望这可以帮到你。