写了代码后出现了3次错误,以下我来教大家解决。
第一个问题:
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.
Exception in thread "main" java.sql.SQLException: 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 specific time zone value if you want to utilize time zone support.
大概意思就是说:引用了弃用的mysql 驱动配置,新的配置是 ****,所以只需要将旧的配置替换成新的就可以了
注册数据库的驱动改为: DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
第二个问题:
Exception in thread "main" java.sql.SQLException: 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 specific time zone value if you want to utilize time zone support.
该错误为是系统时间错误,只需要在后面加上?serverTimezone=GMT%2B8
String url = "jdbc:mysql://localhost:3306/chapter01?serverTimezone=GMT%2B8";
第三个问题:
Exception in thread "main" java.sql.SQLException: Can not call getNString() when field's charset isn't UTF-8
at com.mysql.cj.jdbc.result.ResultSetImpl.getNString(ResultSetImpl.java:1034)
at com.mysql.cj.jdbc.result.ResultSetImpl.getNString(ResultSetImpl.java:1041)
at chapter01.Example01.main(Example01.java:28)
第一时间我以为是我的字符集不是utf-8 进入数据库后 更改字符集 再次运行发现还是报错,仔细分析错误发现 ,是gstNString 并且返回值为null 然后查看代码 。最后将getNString改为getString解决问题。
getString和getNString的区别:
getNString:
在java中,String是为了获得setResult对象当前行指定的列的值。
访问NCHAR NVARCHAR LONGNVRCHAR列时可使用此方法。
getString:
相比之下,getNString()如果查询了属性不为NCHAR、NVARCHAR、LONGNVARCHAR的字段,会报错。
而getString()可以查询所有,并不会报错。若非字符或字符串,则会toString一下。
好了今天的错误解决到此,谢谢大家观看。
忘了给大家附上代码:
package chapter01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Example01 {
public static void main(String[] arg) throws SQLException {
// 注册数据库驱动
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
// 通过DriverManager获取数据库连接
String url = "jdbc:mysql://localhost:3306/chapter01?serverTimezone=GMT%2B8";
String username = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
String sql = "select * from users";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("id name password email brithday");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
String brithday = rs.getString("brithday");
System.out.println(id + "|" + name + "|" + psw + "|" + email + "|" + brithday);
}
rs.close();
stmt.close();
connection.close();
}
}
成功了!