JDBC

报错信息:
在使用mysql-connector-java-6.0.6连接mysql数据库的时候,出现了报错:The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.

报错原因:
顾名思义,服务器的时区值”?й???????无法识别或代表多个时区。您必须配置服务器或驱动程序(通过serverTimezone配置属性)使用一个更具体的时区值如果你想利用时区支持。说白了,没有配置时区,有可能出现问题。

解决方案:
在通过在数据库连接URL后,加上?serverTimezone=UTC 

为什么是UTC

环境需要:如要维护多国环境如中美,时区一致便与维护 

避免风险:避免PDT时区换算出错

实际案例:
1. xxx.properties类型配置文件,如spring配置文件,类似如下配置即可

spring.datasource.url=jdbc:mysql://localhost:3306/chat?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
2.xxx.xml 类型配置文件,如mybatis的配置文件mybatis.cfg.xml,需要注意:xml文件不能识别分割符“&”,需用“&”替代,否则将报错:org.xml.sax.SAXParseException; lineNumber: 30; columnNumber: 109; 对实体 "serverTimezone" 的引用必须以 ';' 分隔符结尾。配置示例如下:

<property name="url" value="jdbc:mysql://localhost:3306/mysql?useUnicode=true&amp;serverTimezone=UTC"

package Jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class demo {
    //驱动管理器
    //mysql url
public static void main(String[] args) {

    //注册驱动程序、时区一定要加上
    String url="jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
    
    String username="root";
    String password="wang18339401841.";
    
    try {
        //获得连接
        Connection conn=DriverManager.getConnection(url, username, password);
        
        //创建语句对象(解耦合)
        Statement st=conn.createStatement();
        
        String sql = "insert test values(2,'wang',20)";
        
        //执行SQL语句
        st.execute(sql);
        //
        System.out.println("over");
        
        //释放资源
        st.close();
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
            
    
}
}

 JDBC

 ------------------------------------

  1.java database connection.

  2.规范,都是借口。

  3.引入驱动程序。

    jar,类库,对SQL规范的实现。

  4.Connection

    连接,相当于Session==Socket

  5.Statement

    语句,相当于InputStream

  6.使用JDBC的过程

      a.注册驱动和获得连接

        

/**
     * 开启连接
     * @return
     */
    public static Connection openConnection() {
        try {
            //获得连接
            String url="jdbc:mysql://localhost:3306/mytest?serverTimezone=UTC";
            String username="root";
            String password="wang18339401841.";
            return DriverManager.getConnection(url, username, password);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

      b.创建Statement语句

        

Statement st =conn.createStatement():

      c.调用Statement执行sql语句

       

st.execute(sql);
ResultSet rs=st. st.executeQuery(sql);

      e.遍历ResultSet

while(rs.next()){
    rs.getInt(1);
    rs.getString("name");
}
原文地址:https://www.cnblogs.com/King-boy/p/10981348.html