Tag Archives: JDBC

[Solved] error {dataSource-1} init error java.sql.SQLException: com.mysql.cj.jdbc.Driver

error {dataSource-1} init error java.sql.SQLException: com.mysql.cj.jdbc.Driver

July 08, 2019 2:39:14 PM com.alibaba.druid.pool.DruidDataSource error
WARNING:error {dataSource-1} init error java.sql.SQLException: com.mysql.cj.jdbc.Driver
	at com.alibaba.druid.util.JdbcUtils.createDriver(JdbcUtils.java:520)
	at com.alibaba.druid.pool.DruidDataSource.init(DruidDataSource.java:583)
	at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:915)
	at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:911)
	at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:98)
	at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151)
	at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
	at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:598)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:655)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:686)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:698)
	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:776)
	at edu.haizi.dao.UserDao.login(UserDao.java:17)
	at edu.haizi.test.UserDaoTest.testLogin(UserDaoTest.java:15)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at com.alibaba.druid.util.JdbcUtils.createDriver(JdbcUtils.java:518)
	... 36 more

July 08, 2019 2:39:14 PM com.alibaba.druid.pool.DruidDataSource info
MESSAGES:{dataSource-1} inited

org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: com.mysql.cj.jdbc.Driver

	at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81)
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:598)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:655)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:686)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:698)
	at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:776)
	at edu.haizi.dao.UserDao.login(UserDao.java:17)
	at edu.haizi.test.UserDaoTest.testLogin(UserDaoTest.java:15)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.sql.SQLException: com.mysql.cj.jdbc.Driver
	at com.alibaba.druid.util.JdbcUtils.createDriver(JdbcUtils.java:520)
	at com.alibaba.druid.pool.DruidDataSource.init(DruidDataSource.java:583)
	at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:915)
	at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:911)
	at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:98)
	at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151)
	at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
	at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
	... 29 more
Caused by: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at com.alibaba.druid.util.JdbcUtils.createDriver(JdbcUtils.java:518)
	... 36 more


Process finished with exit code -1

Solution: the version of MySQL under windows is higher than idea, which makes the version incompatible

Modify Maven dependency package

Original version 5.1.9

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>

Modify to a later version

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>

[Solved] Error updating database. Cause: java.sql.SQLException: Incorrect integer value: ‘**‘ for column

### Error updating database. Cause: java.sql.SQLException: Incorrect integer value: ‘**‘ for column

Type Exception Report

Message Request processing failed; nested exception is org.apache.ibatis.exceptions.PersistenceException:

Description The server encountered an unexpected condition that prevented it from completing the request.

Exceptions

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.sql.SQLException: Incorrect integer value: '刘文' for column 'name' at row 1
### The error may exist in com/bjpowernode/dao/StudentDao.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into student(name,age) values(?,?)
### Cause: java.sql.SQLException: Incorrect integer value: '刘文' for column 'name' at row 1
	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
	org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)


org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.sql.SQLException: Incorrect integer value: '刘文' for column 'name' at row 1
### The error may exist in com/bjpowernode/dao/StudentDao.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into student(name,age) values(?,?)
### Cause: java.sql.SQLException: Incorrect integer value: '刘文' for column 'name' at row 1
	org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:199)
	org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:184)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	java.lang.reflect.Method.invoke(Method.java:498)
	org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
	com.sun.proxy.$Proxy14.insert(Unknown Source)
	org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:278)
	org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:62)
	org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
	com.sun.proxy.$Proxy15.insertStudent(Unknown Source)
	com.bjpowernode.service.impl.StudentServiceImpl.addStudent(StudentServiceImpl.java:19)
	com.bjpowernode.controller.StudentController.addStudent(StudentController.java:26)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	java.lang.reflect.Method.invoke(Method.java:498)
	org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)


java.sql.SQLException: Incorrect integer value: '刘文' for column 'name' at row 1
	com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
	com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
	com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
	com.mysql.cj.jdbc.ClientPreparedStatement.execute(ClientPreparedStatement.java:371)
	com.alibaba.druid.pool.DruidPooledPreparedStatement.execute(DruidPooledPreparedStatement.java:498)
	org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:47)
	org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
	org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
	org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
	org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
	org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:197)
	org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:184)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	java.lang.reflect.Method.invoke(Method.java:498)
	org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
	com.sun.proxy.$Proxy14.insert(Unknown Source)
	org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:278)
	org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:62)
	org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
	com.sun.proxy.$Proxy15.insertStudent(Unknown Source)
	com.bjpowernode.service.impl.StudentServiceImpl.addStudent(StudentServiceImpl.java:19)
	com.bjpowernode.controller.StudentController.addStudent(StudentController.java:26)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	java.lang.reflect.Method.invoke(Method.java:498)
	org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
):Note that the full stack information for the main issue can be viewed in the server logs

 

Solution:

The reason is that I mistakenly wrote the name type as int type. Open navicate to find the created table, right-click to find the design table, and change the name type to varchar

 

[Solved] Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException

Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException Error Messages:

Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at sun.reflect.GeneratedConstructorAccessor28.newInstance(Unknown Source) ~[na:na]
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2234) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2258) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ~[mysql-connector-java-8.0.13.jar:8.0.13]
	... 9 common frames omitted

In fact, this error message is to use version 5.1.33 of MySQL JDBC Driver with UTC time zone. Servertimezone must be explicitly specified in the connection string.

Properties configuration file before modification:

server.port=8080

#jdbc
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb09
spring.datasource.username=root
spring.datasource.password=root

#MyBatis
mybatis.mapper-locations=classpath:com/test/dao/*.xml
mybatis.type-aliases-package=com.test.domain

After modification

server.port=8080

#jdbc
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb09?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

#MyBatis
mybatis.mapper-locations=classpath:com/test/dao/*.xml
mybatis.type-aliases-package=com.test.domain

Modify:

[Solved] JDBC error: Communications link failure

Change url: In addition?useUnicode=true& CharacterEncoding=UTF-8& serverTimezone=UTC”

 <!-- Database connection pooling -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/user_db?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

Solutions to errors in the final running of JDBC programming

An error is reported at the end of JDBC programming:

Exception in thread “main“ java.sql.SQLException: Unknown initial character set index ‘255‘ received

  resolvent:

When establishing a connection between JDBC and the database, add the following after the URL:

?useUnicode=true&characterEncoding=utf-8

As shown in the figure:

Add reason:

        Mysql database uses GBK coding, while the project database uses UTF-8 coding.

org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null

preface

        The spring boot project uses the mybatis plus framework.

Phenomenon

        When I used mappr to execute the method updatebyid again, the following error occurred

nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='et.props', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.postgresql.util.PSQLException: No hstore extension installed.
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='et.props', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #4 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.postgresql.util.PSQLException: No hstore extension installed.

Problem location

        Through the literal meaning of the exception, we can understand it as a mybatis type error.

        Following up with debug, we found that an exception occurred when setting typehandler for one of the fields, indicating that there is no type that can identify the field.

  Cause analysis

        We now check the type of this field in the entity class and find that it is a map type

          View the type of this field setting in the database  , You can see that the JSON type is stored in the database

  Solution

        Set typehandler and JDBC type for entity class

@TableField(el = "props,jdbcType=OTHER,typeHandler=com.embracesource.cloud.fsgw.entity.HashMapJsonTypeHandler")
private Map<String, Object> props;

        Hashmapjsontypehandler class

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class HashMapJsonTypeHandler extends BaseTypeHandler<Map<String,Object>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String,Object> parameter,
                                    JdbcType jdbcType) throws SQLException {
        PGobject jsonObject = new PGobject();
        jsonObject.setType("json");
        jsonObject.setValue(JSON.toJSONString(parameter));
        ps.setObject(i, jsonObject);
    }

    @Override
    public Map<String,Object> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {

        return JSON.parseObject(rs.getString(columnName), HashMap.class);
    }

    @Override
    public Map<String,Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

        return JSON.parseObject(rs.getString(columnIndex), HashMap.class);
    }

    @Override
    public Map<String,Object> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {

        return JSON.parseObject(cs.getString(columnIndex), HashMap.class);
    }
}

         Start the project again and find the problem to be solved

Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communicat

Solution: when connecting to the database, change usessl = true to usessl = false. Of course, if usessl = true is not written, it is true by default.

Note: however, I don’t know why I did it. What’s more, the tutorial I read only uses true, and why I report an error. If a boss sees it, he hopes to answer it.

Java.sql.sqlexception: unable to read more data from socket

Some online is to modify the configuration, I tried no effect, later found that because the query statement, the subquery contains the order statement, the subquery Order to remove the problem. This statement through the PLSQL direct query is no problem, but through the jdbc background query will report an error.
error:
exe_sql = select * from (select t1.*, rownum r from ( select device_site.major,device_site.site_code,device_site.type_code,device_site.site_type,device_site.site_name,device_site.site_prop,device_site.site_level,device_site.site_allname,device_site.major_code,device_site.site_comname,device_site.rule_name,device_site.special,device_site.install_site,device_site.arrive,device_site.pinyin,device_site.house_code,device_site.dept_name,device_site.area,device_site.photo,device_site.mi_num,device_site.wmi_num,device_site.site_supe_code,device_site.memo,device_site.site_id from device_site where (site_id like (select site_id || ‘%’ from water_reg where water_id=?)) order by site_code asc) t1 where rownum < 51) t2 where t2.r > 0
where_type = string
where_value = eam-704-556
2021-06-28 13:55:31 jxstar: org.jxstar.dao.DaoUtil.showException on line: -1
java.sql.SQLException:Unable to read more data from a socket
at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1200)
at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1155)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:279)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:205)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:861)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1145)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1267)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3449)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3493)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1203)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.jxstar.dao.JsonDao.query(Unknown Source)
at org.jxstar.service.query.GridQuery.query(GridQuery.java:139)
at sun.reflect.GeneratedMethodAccessor40.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.jxstar.service.control.ControlerUtil.invoke(Unknown Source)
at org.jxstar.service.control.ControlerUtil.executeEvent(Unknown Source)
at org.jxstar.service.control.ServiceControllerImp.execute(Unknown Source)
at org.jxstar.control.action.CommonAction._$1(Unknown Source)
at org.jxstar.control.action.CommonAction.execute(Unknown Source)
at org.jxstar.control.AjaxController.processRequest(Unknown Source)
at org.jxstar.control.AjaxController.doPost(Unknown Source)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jxstar.control.filter.JxstarFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jxstar.control.filter.XSSFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:610)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:503)
at java.lang.Thread.run(Thread.java:745)
2021-06-28 13:55:31 jxstar: org.jxstar.service.query.GridQuery.query on line: 141
warn: grid query error!
2021-06-28 13:55:31 jxstar: org.jxstar.service.control.ServiceControllerImp.execute on line: -1
org.jxstar.dao.transaction.TransactionException: tranobject.rollback:Unable to read more data from a socket
at org.jxstar.dao.transaction.TransactionObjectImp.rollback(Unknown Source)
at org.jxstar.dao.transaction.TransactionManagerImp.rollbackTran(Unknown Source)
at org.jxstar.service.control.ServiceControllerImp.execute(Unknown Source)
at org.jxstar.control.action.CommonAction._$1(Unknown Source)
at org.jxstar.control.action.CommonAction.execute(Unknown Source)
at org.jxstar.control.AjaxController.processRequest(Unknown Source)
at org.jxstar.control.AjaxController.doPost(Unknown Source)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jxstar.control.filter.JxstarFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jxstar.control.filter.XSSFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:610)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:503)
at java.lang.Thread.run(Thread.java:745)
2021-06-28 13:55:34 jxstar: request is have file upload: false

MySql 8.x java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

Questions

Error in remote connection to MySQL 8.0 using mybatis plus to reverse generate entity class codegenerator

Exception in thread "main" java.lang.RuntimeException: java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
	at com.baomidou.mybatisplus.generator.config.DataSourceConfig.getConn(DataSourceConfig.java:170)
	at com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder.<init>(ConfigBuilder.java:110)
	at com.baomidou.mybatisplus.generator.AutoGenerator.execute(AutoGenerator.java:96)
	at com.dev.docker.config.CodeGenerator.main(CodeGenerator.java:125)
Caused by: java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
	at com.baomidou.mybatisplus.generator.config.DataSourceConfig.getConn(DataSourceConfig.java:168)
	... 3 more

reason

Official website: https://mysqlconnector.net/connection-options/

         If the user account uses sha256_ Password authentication, transmission must protect the password; TLS is the preferred mechanism, but if it is not available, RSA public key encryption will be used. To specify the RSA public key of the server, use the serverrsapublickeyfile connection string setting, or set allowpublickeyretrieval = true to allow clients to automatically request the public key from the server. Note that allowpublickeyretrieval = true may allow malicious agents to perform mitm attacks to obtain plaintext passwords, so it is false by default and must be explicitly enabled.

         Because allowpublickeyretrieval and allowpublickey retrieval are false by default, it is necessary to add “allowpublickeyretrieval = true” on the JDBC connection

Solutions

Add “allowpublickeyretrieval = true” to JDBC connection

jdbc:mysql://xxxx/xxx?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true

Solution to javax.naming.noinitialcontextexception error

When using DBCP to configure data sources, a test class was written. In the test class, DBCP was called to get the database connection error: javax.naming.NoInitialContextException: Need to specify class name in environment or or in,

Check whether the dependent jar package is imported:
commons-dbcp2-2.8.0. Jar
commons-pool2-2.10.0. Jar
mysql8.0 jar package
mysql5.0 jar package

Test code:

package test;

import org.junit.Test;
import tools.DataSourceUtil;

import java.sql.Connection;

public class test {
    @Test
    public void test(){
        Connection connection = DataSourceUtil.getConnection();
        System.out.println(connection);
    }
}

Database source code:

package tools;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceUtil {

    // Get the connection
    public static Connection getConnection() {
        // ctrl + alt + t --- select 6
        // instantiate the object of the initial context
        Connection connection = null;
        try {
            InitialContext initialContext = new InitialContext();
            // Get the data in the configuration and get the object object
            Object lookup = initialContext.lookup("java:comp/env/jdbc/easybuy");
            // unboxing strong turn to get the connection pool
            DataSource ds = (DataSource) lookup;
            // get the connection pool to give me a connection
            connection = ds.getConnection();
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        // Return to link
        return connection;
    }

    // close connection
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

Bug map:

reason:

When DBCP is used to connect to the database, the main function is always used to test. The initialcontext is only available in the context of the web application server. While the configuration file is in the web directory, it is obvious that if initialcontext wants to access the configuration file, it must run on the web server to connect to the database and get the connection object

It can’t be tested directly with the main function, it can only be displayed in Tomcat or servlet or JSP

Running results:

#Successfully get the connection object!

Problems in connecting mysql8.0 in IDEA [How to Solve]

MySQL 5.7 has always been used before, because some changes have taken place after updating to MySQL 8.0, and some information needs to be modified in the configuration of MySQL driver connection.

In MySQL version 5.7, getting the database connection is realized by the following code

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名称","数据库账号","数据库密码");

In MySQL 8.0, you need to add a time zone. The implementation code is as follows

connection = DriverManager.getConnection(” jdbc:mysql :// localhost:3306/ Database name true & amp; characterEncoding=utf-8&& amp; serverTimezone=GMT%2B8& Usessl = false “,” database account “,” database password “);

After completing the above modification, you can perfectly solve the connection problem of mysql8.0. The connection is successful, as shown in the figure below