前置条件:下载并加载数据库驱动jar包
一:JDBC开发流程
1.加载注册JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
Class.forName用于加载指定的JDBC驱动类
2.创建数据库连接
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&charecterEncoding=UTF-8&SserverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true",
"root",
"092020");
DriverManager用于注册/管理JDBC驱动程序,Connection对象用于JDBC与数据库的网络通信对象, DriverManager.getConnection(连接字符串,用户名,密码)
Mysql连接字符串:jdbc:mysql://[主机ip][端口]/数据库名?参数1=值1&参数2=值2&...
参数名 | 建议参数值 | 说明 |
useSSL | true(生产)false(开发) | 是否禁用ssl |
useUnicode | true | 启用unicode编码传输数据 |
characterEncoding | UTF-8 | 使用UTF-8编码传输数据 |
serverTimezone | Asia/Shanghai | 使用东8区时间,UTC+8 |
allowPublicKeyRetrieval | true | 允许从客户端获取公钥加密传输 |
3.创建Statement对象
Statement stmt = conn.createStatement(); //执行sql语句
ResultSet rs = stmt.executeQuery("select * from employee"); //ResultSet结果集
4.遍历查询结果
while(rs.next()){
Integer eno = rs.getInt("eno");
String ename = rs.getString("ename");
Integer salary = rs.getInt("salary");
String dname = rs.getString("danme");
System.out.println(eno+"——"+ename+"——"+salary+"——"+dname);
}
5.关闭连接,释放资源
conn.close();
6.对代码进行异常处理
7.运行结果
8.数据表
sql文件,需要的自取:
https://download.youkuaiyun.com/download/TT9200/27895401
https://pan.baidu.com/s/1DVI8KuZ2chb5Td6xZo4gUQ
提取码:1234
二:基本异常
没有导入驱动包:
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
数据库不存在:
java.sql.SQLSyntaxErrorException: Unknown database 'test'
数据库端口错误:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
密码错误:
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
用户不存在:
java.sql.SQLException: Access denied for user 'rt'@'localhost' (using password: YES)