如何从SQL查询(Jooq,Java)获取列名 [英] How to obtain column names from SQL query (Jooq,Java)

查看:360
本文介绍了如何从SQL查询(Jooq,Java)获取列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我从SQL查询获取值有问题(在Java中,使用jooq库)?

Hello I have a problem with obtain values from SQL query (in Java with using library of jooq)?

create table `filetest`(`id` int not null auto_increment, `Meno` varchar(21) null, `Priezvisko` varchar(24) null, `Vek` int null, constraint `pk_filetest` primary key (`id`))

insert into `filetest` (`Meno`, `Priezvisko`, `Vek`) values ('Jack', 'Daniels', '21')

我需要获取(解析/获取)的是值:Meno,Priezvisko,Vek. 是否有可能以某种方式从表的列的sql查询名称中获取它(使用某些jooq方法)?

What I need to obtain (parse/get) are values: Meno, Priezvisko, Vek. Is it possible somehow get it from sql query name of columns of table (with some jooq method)?

推荐答案

从您的问题开始,我假设您要使用

From your question, I'm assuming you'd like to use the jOOQ parser API to parse your SQL string and then extract the column names from jOOQ's meta model.

当前(从jOOQ 3.11开始),元模型无法通过公共API获得.您只能通过使用 VisitListener ,这是每个 QueryPart (即表达式树元素).该示例实现可以为您提供一个想法:

Currently (as of jOOQ 3.11), the meta model is not available through a public API. You can access it only by means of using a VisitListener, which is an SPI that is called on every QueryPart (i.e. expression tree element) that is contained in the meta model. This example implementation can give you an idea:

import org.jooq.*;
import org.jooq.impl.*;

public class Columns {
    public static void main(String[] args) {
        var parser =
        DSL.using(new DefaultConfiguration().set(new DefaultVisitListener() {
            @Override
            public void visitStart(VisitContext ctx) {
                if (ctx.queryPart() instanceof Field
                        && !(ctx.queryPart() instanceof Param))
                    System.out.println(((Named) ctx.queryPart()).getQualifiedName());
            }
        })).parser();

        System.out.println("Query 1");
        System.out.println("-------");
        parser.parseQuery("create table `filetest`(`id` int not null auto_increment, `Meno` varchar(21) null, `Priezvisko` varchar(24) null, `Vek` int null, constraint `pk_filetest` primary key (`id`))").getSQL();

        System.out.println();
        System.out.println("Query 2");
        System.out.println("-------");
        parser.parseQuery("insert into `filetest` (`Meno`, `Priezvisko`, `Vek`) values ('Jack', 'Daniels', '21')").getSQL();
    }
}

它将打印:

Query 1
-------
"id"
"Meno"
"Priezvisko"
"Vek"
"id" -- Field is referenced again from the constraint

Query 2
-------
"Meno"
"Priezvisko"
"Vek"

当然,另一个选择是使用反射来访问jOOQ的内部.

Another option is, of course, to use reflection to access jOOQ's internals.

这篇关于如何从SQL查询(Jooq,Java)获取列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆