未配置连接

No connection configured

我如何配置连接来修复这个错误?我使用 MySQL 和 jdbc.

public static void saveCallLink(String oktell_login, String link)
        throws SQLException {
    Connection conn = DBConnection.getDataSource().getConnection();
    DSL.using(conn)
            .insertInto(CALLS)
            .columns(CALLS.USER_ID, CALLS.CALL_LINK)
            .values(
                    DSL.select(USERS.ID)
                            .from(USERS)
                            .where(USERS.OKTELL_LOGIN.equal(oktell_login))
                            .fetchOne().value1()
                    , link
            ).execute();
    conn.close();
}

抱歉,已添加日志。

org.jooq.exception.DetachedException: 无法执行查询。未配置连接 org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:316) org.jooq.impl.AbstractResultQuery.fetchLazy(AbstractResultQuery.java:365) org.jooq.impl.AbstractResultQuery.fetchLazy(AbstractResultQuery.java:352) org.jooq.impl.AbstractResultQuery.fetchOne(AbstractResultQuery.java:517) org.jooq.impl.SelectImpl.fetchOne(SelectImpl.java:2868) ru.avito.model.CallModel.saveCallLink(CallModel.java:33) ru.avito.web.OktellListener.saveCallRecord(OktellListener.java:31) sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法) sun.reflect.NativeMethodAccessorImpl.invoke(未知来源) sun.reflect.DelegatingMethodAccessorImpl.invoke(来源不明) java.lang.reflect.Method.invoke(来源不明)

你的错误在这里:

DSL.using(conn)
   .insertInto(CALLS)
   .columns(CALLS.USER_ID, CALLS.CALL_LINK)
   .values(
       DSL.select(USERS.ID)
          .from(USERS)
          .where(USERS.OKTELL_LOGIN.equal(oktell_login))
          .fetchOne().value1() // This query cannot be executed
       , link
   ).execute();

您 运行 在 INSERT 语句中间的查询无法执行,因为它没有附加 Configuration (上下文)。作为一般经验法则,永远记住:

  • DSLContext 创建 "attached" 到 DSLContext.configuration() 的查询,因此可以直接执行
  • DSL 创建 "unattached" 的查询,因此无法执行,只能嵌入到其他查询中

有两种解决方案:

1。附上嵌套的 select

DSL.using(conn)
   .insertInto(CALLS)
   .columns(CALLS.USER_ID, CALLS.CALL_LINK)
   .values(
       DSL.using(conn) // Use DSLContext, not DSL here
          .select(USERS.ID)
          .from(USERS)
          .where(USERS.OKTELL_LOGIN.equal(oktell_login))
          .fetchOne().value1()
       , link
   ).execute();

不过请注意,这将 运行 来自客户端的两个独立查询,这可能不是您真正想要的。你想要:

2。将您的 SELECT 嵌套在 INSERT 语句

DSL.using(conn)
   .insertInto(CALLS)
   .columns(CALLS.USER_ID, CALLS.CALL_LINK)
   .values(
       DSL.field(
           DSL.select(USERS.ID)
              .from(USERS)
              .where(USERS.OKTELL_LOGIN.equal(oktell_login))
       )
       , link
   ).execute();

这现在与以下单个 SQL 查询相同:

INSERT INTO calls (user_id, call_link)
VALUES ((SELECT id FROM users WHERE oktell_login = :oktell_login), :link)