"***"部分是自己的数据库 密码以及需要查询的列名
localhost:3306/***
:数据库名称
password="***"
:当前需要链接的数据库的密码
FROM ***
:需要查询的数据中心的任意一个表的表名
getObject("***")
:需要查询的表的列
import java.sql.*;
public class JDBCFirst {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1加载驱动
Class.forName( "com.mysql.cj.jdbc.Driver" ) ;//固定写法,加载驱动
//2用户信息利和url
//? 链接参数
//useUnicode=true 使用Unicode编码,这样就能使用中文
//characterEncoding=utf8 设置字符集编码,防止乱码
//useSSL=true 使用安全的链接
String url = "jdbc:mysql://localhost:3306/***?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8";
String username="root";
String password="***";
//3连接数据库对象
Connection connection = DriverManager.getConnection(url,username,password);//connection代表数据库
//4.执行sQL的对象
Statement statement = connection.createStatement();//statement执行sql对象
//5.执行sQL的对象去执行sQL,可能存在结果,查看返回结果
String sql="SELECT * FROM ***";
ResultSet resultSet = statement.executeQuery(sql);//statement执行完后返回一个结果集
while(resultSet.next()){
System.out.println(resultSet.getObject("***"));
}
//6、释放连接
resultSet.close();
statement.close();
connection.close();
}
}
可能遇到的问题
问题1
报错:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
遇到这样的错误是没有引入mysql-connector-java-x.x.x-bin.jar
的问题
问题2
报错:
Exception in thread "main" java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone.
遇到这样的报错是系统时间错误,只需要在访问数据库的Url后面加上以下的语句即可:
&serverTimezone=GMT%2B8
问题3
报错:
Fri Sep 07 17:48:01 GMT+08:00 2018 WARN: Establishing SSL connection without server's identity verification
如果遇到这样的问题,这是时间报错,没有指定明确的时区,是因为新版的mysql会询问是否SSL连接,返回一个Boolean值,我们需要手动指定true或者false。