1. 异常: 程序 被中断了, ----程序发生异常后, 不会继续向下执行, 而是 终止 要做 异常处理: try catch finally throw 抛出异常, throw 一般写在方法体里, 具体用法 throw new 异常类名(); throws: 声明异常, 写在 方法声明的地方, 位于参数列表的后面 语法: try{ } catch(){ } 或 try{ } finally{ } 或 try{ // 可能发生异常的代码 }catch(){ }finally{ // 必须要关闭的,必须中终止的 } 注意: catch 可以写多个, 但 要注意 , 从小往大写, 一般 Exception 写在最后 当 有多个catch时 ,从上到下 逐个匹配, 谁匹配执行谁,其余不做 2. Exception 类: 异常 Error 类: 错误,程序终止, Throwable 是 所有 异常及错误的父类 Exception 又分为 RuntimeException 和 非 RuntimeException RuntimeException 运行时 异常 3. JDBC maven 项目中 src/main/java ----存放 java 代码 src/test/java ---- 存放 单元测试用例 在 src/test/java 下 创建类, 随意定义方法, 在方法上 增加 @Test,则 该方法就可以运行 4. sql select * from student; 建立 emp (eno,ename,borndate,phone,deptid)与 dept(id,name) 表 每个表增加 5条数据 5. jdbc a. 在pom.xml 增加 依赖 mysql-connector-java依赖 b. 编写 实体类, 按照 数据库表 生成对应的 类 数据库类型 java 类型 int int varchar String datetime java.util.Date 注意事项: 属性名 采用 驼峰式命名法 实体类 要求采用 封装的写法(属性私有,get/set方法) 实体类要求有 无参及全参构造 实体类要 重写 toString()
package entity;
/**
* 部门类
*/
public class Dept {
private int id; // 部门编号
private String name;//部门名称
public Dept() {
}
public Dept(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Dept{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package util;
import java.sql.*;
/**
* 连接数据库的工具类
*/
public class DBUtils {
/**
* 测试数据库连接
*/
public void testConn() throws Exception {
String username= "root"; //用户名
String password = "root";// 密码
String url="jdbc:mysql://localhost:3306/xin1";// 数据库的连接地址
String driver = "com.mysql.cj.jdbc.Driver"; // 注意 8-5.5 写法不同
//利用 java 反射机制 获得数据库的连接
Class.forName(driver); // 加载驱动
Connection connection = DriverManager.getConnection(url,username,password);// 获得数据库的连接对象
Statement statement = null;
ResultSet rs = null;
if (connection !=null){
System.out.println("-----------进行数据的查询-------");
System.out.println("------------数据库的信息展示----------");
System.out.println("----------------查询结束--------");
// 编写查询sql
String sql = "select * from dept";
statement = connection.createStatement(); // 获得 Statement对象
rs = statement.executeQuery(sql); // 执行 sql,进行 查询
// 因为 sql的执行结果有 多个, 因此 采用 循环的方式 逐行获取
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("编号-------"+id+"-------部门名称----"+name);
}
}
// 关闭连接
if(rs !=null){
rs.close();
}
if(statement!=null){
statement.close();
}
if(connection !=null){
connection.close(); //关闭连接
}
System.out.println("-----查询执行完毕-----");
}
}
@Test
public void a2(){
DBUtils dbUtils = new DBUtils();
try{
dbUtils.testConn();
}catch (Exception e){
System.out.println("-----"+e.getMessage());
}
}