使用Spring和DBCP和MySQL设置连接时区

raf*_*ira 13 java mysql timezone spring jdbc

我的环境

  • Java 5
  • 春天2.5.5
  • DBCP DataSource (org.apache.commons.dbcp.BasicDataSource)
  • MySQL的

类似帖子

链接

我的问题

  • 我需要在我的连接上设置时区,旨在防止处理TIMESTAMP列时的转换.

我的想法/研究

  • DBCP连接池没有提及时区周围的任何内容.链接

  • 我调查,并认为这是确定在描述岗位,示范是:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="URL" value="${database.url}" /> 
    <property name="user" value="${database.username}" /> 
    <property name="password" value="${database.passwd}" /> 
    <property name="connectionCachingEnabled" value="true"/>
    <property name="sessionTimeZone" value="GMT-3"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

求助区:)

  • 但这不行!
  • 我想要的是一种简单的方法,优先使用Spring在jdbc连接上配置时区.

提前感谢任何帮助/提示/建议/知识分享


解:

我的解决方案基于此帖子收集的提示!谢谢大家!

(...)
@Override
public Connection getConnection() {
    Connection conn = null;
    Statement statement = null;
    try {
        conn = super.getConnection();
        statement = conn.createStatement();
        statement.execute("SET time_zone = \'" + timezone+"\'");
    } catch (SQLException e) {
        LOG.fatal("Error while SET time_zone", e);
    } finally {
        try {
            statement.close();
        } catch (SQLException e) {
            LOG.warn("Error while closing statement", e);
        }
    }
    if(LOG.isDebugEnabled())
        LOG.debug("SET time_zone("+timezone+") for connection, succeed!");
    return conn;
}
(...)
Run Code Online (Sandbox Code Playgroud)

并在我的Spring配置文件中:

<bean id="dataSource" class="com.my.package.dbcp.TimezoneEnabledDataSource" destroy-method="close">
    (...)
    <property name="timezone" value="${database.timezone}" />
    (...)
</bean>
Run Code Online (Sandbox Code Playgroud)

我希望这篇文章可以帮助将来的某个人.有问题ping我!

Cha*_*shu 7

您应该能够将相同的SQL语句放在DBCP配置元素的initConnectionSqls属性中.只需将其添加到DBCP配置元素即可

<property name="initConnectionSqls" value="SET time_zone = '${database.timezone}'"/>
Run Code Online (Sandbox Code Playgroud)

根据您的DBCP版本,您可能必须使用connectionInitSqls作为属性名称.此信息直接来自DBCP配置文档.


Boz*_*zho 6

如果数据源没有这样的属性,您可以扩展它并添加该属性:

public TimezoneEnabledDataSource extends BasicDataSource {
    private String timezone;
    //getter and setter for it

    @Override    
    public Connection getConnection() {
        Connection c = super.getConnection();
        // execute a query: SET time_zone = '-8:00'
        return c;
    }
}
Run Code Online (Sandbox Code Playgroud)

有关查询详细信息,请参见http://www.electrictoolbox.com/mysql-set-timezone-per-connection/.

MySQL文档写道:

每个连接时区.连接的每个客户端都有自己的时区设置,由会话time_zone变量给出.最初,会话变量从全局time_zone变量中获取其值,但客户端可以使用以下语句更改其自己的时区:

mysql> SET time_zone = timezone;

您还可以检查c3p0是否没有内置内容.