package JDBCTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCtest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
String driver = "com.mysql.cj.jdbc.Driver";
Class.forName(driver);
//java会自动将驱动对象注册到DriverManager类中
//2.连接数据库
String url="jdbc:mysql://127.0.0.1:3306/shopping?serverTimezone=UTC ";
Connection connection = DriverManager.getConnection(url, "root", "123456");
//3.通过Statement执行sql语句
Statement statement1 = connection.createStatement();
// PreparedStatement statement = connection.prepareStatement("select * from cartitem");
ResultSet resultSet = statement1.executeQuery("select * from cartitem");
while (resultSet.next()){
String goodName=resultSet.getString("good_name");
String cartId = resultSet.getString("cart_id");
System.out.println(goodName);
System.out.println(cartId);
}
}
}
其中要注意的是,我最开始的URL中没有 serverTimezone=UTC
程序报错
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: 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
String url="jdbc:mysql://127.0.0.1:3306/shopping?serverTimezone=UTC " 改成这样即可解决