在Windows7 系統上安裝了MySQL 8.0,而後建立Maven工程,配置pom.xml文件,添加了以下依賴:java
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>mysql
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" >
<property name="" value="" />
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="password@password" />
</dataSource>
</environment>
</environments>sql
運行測試函數進行鏈接測試,出現以下錯誤提示:數據庫
org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 21; columnNumber: 102; 對實體 "characterEncoding" 的引用必須以 ';' 分隔符結尾。apache
上網搜索解決方案,才知道 mybatis 的配置文件中,這裏 url 中的 '&' 符號應當寫成 '&' ,修改後的 url 以下:mybatis
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC" />函數
這樣就能夠正常鏈接了。測試
@Test public void testJDBC() { Connection conn = null; try { String userName = "root"; String passWord = "password@password"; String jdbcUrl = "jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC"; Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(jdbcUrl, userName, passWord); String sql = "select id,countryname,countrycode from country"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String countryname = rs.getString("countryname"); String countrycode = rs.getString("countrycode"); System.out.println(id + "\t" + countryname + "\t" + countrycode); } pstmt.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { System.out.println("Game Over!"); } }
運行測試函數,結果出現以下錯誤:ui
java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near ';characterEncoding=utf-8&useSSL=false&serverTimezone=UTC'.url
嘗試修改 url ,將 '&' 改爲 '&' , 結果就運行正常了,說明 JDBC 方式鏈接 MySQL 不須要對 '&' 進行轉義。
特此記之。