java - 在准备好的语句中获取列名而不是值

标签 java sql swing jdbc

我在准备好的语句中获取列名称而不是值。

这是我的代码:

string q="select ? from EMPLOYEE where salary > ?";

Preparedstatement pst = connectionobject.preparedstatement(q);
pst.setstring(1, "FIRST_NAME");
pst.setint(2, 10000);

当我在 JTable 中打印结果时,它在所有行中显示 FIRST_NAME

最佳答案

这是不可能的,用你的方式来解决你的问题。

像这样更改您的代码:

String att = "FIRST_NAME";

string q="select " + att + " from EMPLOYEE where salary>?";

Preparedstatement pst=connectionobject.preparedstatement(q);
pst.setint(1,10000); 

如果您担心用户可以进行 SQL 注入(inject),而不是使用此解决方案

您应该检查您的列是否存在于表中:

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

如果该列存在,那么您可以像这样继续:

if(column_exist(att)){
   string q="select " + att + " from EMPLOYEE where salary>?";

   Preparedstatement pst=connectionobject.preparedstatement(q);
   pst.setint(1,10000); 
}

在这里了解更多:

MySQL, Check if a column exists in a table with SQL

希望这可以帮助你。

关于java - 在准备好的语句中获取列名而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869380/

相关文章:

java - "parsererror"语法错误 : Unexpected token c

java - 在线 Java 书籍

java - 无法从@OneToMany 集合中删除元素

java - 通用链表 - 如何添加不同的对象

java - 运行我的代码后出现一堆错误

mysql - 为什么 "INTERVAL"不是 IF 语句中的有效语法

sql - 如何在SQL Server 2008中获取时间字段的总和

java - 如何使用文本字段设置椭圆的尺寸?

用于 swing GUI 编程的 Java 类体系结构

java - 如何显示过程调用的进度条