JDBC数据库连接
连接代码
报错分析:
1.无法加载驱动
在Eclipse导入MySQL驱动包
在项目上右键Buildpath–>Add External Archives…
选择自己下载的驱动包,例如mysql-connector-java-5.1.42-bin.jar点击添加,下载保存路径尽量不要太深
2.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.
出现这个的原因是因为 mysql返回的时间总是有问题,比实际时间要早8小时。
解决方法:
“jdbc:mysql://127.0.0.1:3306/pms后面加入
?characterEncoding=utf8&useSSL=true&serverTimezone=UTC”
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.
String Driver=“com.mysql.jdbc.Driver”;
将驱动代码更改为"com.mysql.cj.jdbc.Driver"即可
连接代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySqlJdbcTest{
public static void main(String[] args) {
String Driver="com.mysql.cj.jdbc.Driver";
String url="jdbc:mysql://127.0.0.1:3306/pms?characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
String user="root";
String password="root";
try {
Class.forName(Driver); //捕获异常
try (Connection conn = DriverManager.getConnection(url,user,password)) {
if (!conn.isClosed()) {
System.out.println("Succeeded connecting to the pms");
}
Statement stat = conn.createStatement();
String sql = "select * from person";
ResultSet rs = stat.executeQuery(sql);
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println(" ID" + "\t" + " 姓名");
System.out.println("-----------------");
String name = null;
while (rs.next()) {
name = rs.getString("name");
System.out.println(rs.getInt("id") + "\t" + name);
}
rs.close();
}
} catch (ClassNotFoundException e) {
System.out.println("Sorry,can't find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}