Java连接数据库出现的几个小问题
现在是2018-12-19
使用的驱动包是mysql-connector-java-8.0.13.jar
MySQL是XAMPP中集成的MariaDB-10
由于利用Python爬虫数据保存到数据库中,在Java侧需要调用。鉴于小项目不需要使用MyBatis或者hibernate之类的框架,所以利用原生jdbc进行操作。
public static final String JDBC = "com.mysql.jdbc.Driver";
public static final String DATABASE_NAME = "jdbc:mysql://localhost:3306/spiders";
private static String username = "root";
private static String password = "root";
public static void main(String[] args){
Connection conn = null;
Statement stat = null;
try{
Class.forName(JDBC);
System.out.println("start");
conn = DriverManager.getConnection(DATABASE_NAME, username, password);
stat = conn.createStatement();
String sql = "SELECT * FROM wanfang_data LIMIT 5";
ResultSet set = stat.executeQuery(sql);
while (set.next()){
String title = set.getString("title");
String summary = set.getString("summary");
System.out.println("title: " + title + ";" + "\t" + "summary: " + summary);
}
set.close();
stat.close();
conn.close();
}catch (SQLException e){
e.printStackTrace();
}catch (Exception e1){
e1.printStackTrace();
}
finally {
try{
if (stat != null)
stat.close();
}catch (SQLException e){
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
以上的代码是没有办法做正确运行的,主要是有两个问题
1.驱动代码包名发生的变动,网络上大部分都是未更新的驱动包名,需要将包名更改为"com.mysql.cj.jdbc.Driver";
2.SQLException,有一些乱码和time zone之类的文字提示。
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 specifc time zone value if you want to utilize time zone
support.
经过检查,报错是指本地和jar包时间不一致,需要在数据库地址后添加serverTimezone=GMT,诸如本例就是变成 “jdbc:mysql://localhost:3306/spiders?serverTimezone=GMT”