ja002

这篇博客主要介绍了Java中异常的抛出和处理,包括在main方法内和外部的异常处理。同时,详细讲解了JDBC编程的基础步骤,如设置驱动、建立数据库连接以及执行CRUD操作。
摘要由CSDN通过智能技术生成

(一)异常的抛出和处理:

(1)放在main里

package com.tzr.exception;

import java.util.ArrayList;
public class ExceptionDemo01 {

	public static void main(String[] args) {
		
		try {
			//list目前为空,因为还没有new,是不能使用的
			ArrayList<Integer> list = null;//空指针异常
		
			list.add(34);
			list.add(344);
			
		}catch(NullPointerException e) {
			System.out.println("出现了空指针异常");
            throw e;//抛出异常
		}
		
			
	}

}

(2)放在main外 

自定义处理异常方法
try {
			test(19);
			test(0);
			test(200);//抛出异常后程序停止运行
			test(-90);
			test(-9099);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			
	}
	public static void test(int age) throws Exception  {
		if(age>=0&&age<18) {
			System.out.println("未成年人");
		}else if(age>=18&&age<=150) {
			System.out.println("成年人");
		}else {
			throw new Exception("年龄输入不合法"); //抛出异常
		}
	}
}

(二)JDBC编程

1.建立驱动

2,建立连接

public class JDBCDemo01 {

	public static void main(String[] args) {
		
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");//使用什么驱动连接什么数据库
			
			//String url="jdbc:mysql://localhost:3306/web01";//有时候可能会乱码
			//解决乱码问题
			String url="jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8";
			String user="root";
			String password="root";
			Connection con=DriverManager.getConnection(url,user,password);
			//DriverManager.getConnection(url,user,password);
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

3.进行增删改查操作

public static void main(String[] args) {
		
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");//使用什么驱动连接什么数据库
			
			//String url="jdbc:mysql://localhost:3306/web01";//有时候可能会乱码
			//解决乱码问题
			String url="jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC";
			String user="root";
			String password="root";
			Connection con=DriverManager.getConnection(url,user,password);
			//DriverManager.getConnection(url,user,password);
		
			Statement stmt=con.createStatement();
			ResultSet rs=stmt.executeQuery("select * from user");
			
			while(rs.next()) {
				System.out.println(rs.getInt(1)+","+rs.getString(2)+rs.getString(3));
			}
			
			if(rs!=null)rs.close();
			if(stmt!=null)rs.close();
			if(con!=null)rs.close();
			System.out.println("666");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值