JDBC学习笔记——JDBC MySQL使用时遇到的问题及解决方案(持续更新)

2018.4.22更:

问题1:JDBC MySQL驱动没有正确选择,导致JDBC与MySQL无法正确连接(我使用的是MySQL版本是5.7)

解决方案:驱动选择 mysql—connector—java—8.0.11.jar  问题解决。(驱动需官网下载)

问题2:MySQL链接 url 格式和参数问题
解决方案:url使用jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&characterEncoding=utf8 问题解决。 这个解决方案支持中文插入 ,前提是这个数据库的编码方式是utf8。(如需解决数据库插入中文时出现乱码问题,请继续往下看)
mysql插入中文出现乱码问题解决方案:在MySQL数据库可视化工具(我自己用的是MySQLWorkbench)中将数据库默认编码改为utf8_unicode_ci ,在这之后创建的表都能正常插入中文了。注意,在更改数据库编码方式之前创建的表需手动修改编码方式。手动修改表的编码方式如下:
alter table 表名 charset=utf8,collate=utf8_unicode_ci;//这行命令修改了表的编码方式,之前定义的字符串类型的列还是原来的编码方式还需要继续手动更改,请继续往下看
alter table 需要更改的列名 change 列名 新列名 类型 character set utf8 collate utf8_unicode_ci;


问题3:在进行以下常规获取JDBC中DriverManager运行窗口提示错误

 Class.forName(“com.sql.jdbc.Driver”);
 Connection con=DriverManager.getConnection(url,username,password);
 Statement stmt=con.createStatement();

错误提示:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Sun Apr 22 18:41:17 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

原因:新版本的MySQL驱动类名是 com.mysql.cj.jdbc.Driver 所以当使用 com.mysql.jdbc.Driver 去加载驱动会加载失败。并且新版本的MySQL驱动会自动加载 DriverManager 无需我们再自己手动用Class.forName去加载驱动。
 
解决方案:将加载驱动类名改为 com.mysql.cj.jdbc.Driver 或者直接去掉Class.forName()。

猜你喜欢

转载自blog.csdn.net/weixin_41072833/article/details/80042491
今日推荐