JDBC的连接、封装

这篇博客详细介绍了JDBC连接数据库的步骤,包括关联数据库驱动、注册驱动、建立连接、执行SQL以及处理结果集,并提及了JDBC的封装对于简化代码和方便使用的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JDBC连接数据库

数据库是用于管理数据的,后台是用于根据业务做逻辑处理的,前台显示数据并进行交互
步骤:

1、关联数据库驱动包(不同的数据库使用的驱动包是不一样的)

2、注册驱动(通过反射进行驱动的注册)

3、连接数据库获取数据库连接对象(登录-选择数据库的过程)

4、执行SQL语句

5、处理结果集

6、关闭数据库连接对象
首先需要关联数据驱动包 jar包 跟数据库要匹配

	public static void look() {
		Connection conne =null;
		Statement state =null;
		ResultSet resu =null;
		try {
			//1、注册驱动
			Class.forName(DRIVER);
			//2、连接数据库
			conne = DriverManager.getConnection(URL,USER,PAAWORD);
			//3、定义SQL
			String SQL = "select * from score";
			//4、执行SQL 需要 Statement对象
			state = conne.createStatement();
			//5、执行SQL 获取结果处理结果集
			resu = state.executeQuery(SQL);
			//遍历结果集
			while(resu.next()) {
				int s = resu.getInt("s_id");
				int c = resu.getInt("c_id");
				int sc =resu.getInt("s_score");
				System.out.println(s+"-----"+c+"-----"+sc);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			//关闭
			try {
				if(resu!=null) {
					resu.close();
				}
				if(state!=null) {
					state.close();
				}
				if(conne!=null) {
					state.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
JDBC的封装
//注册驱动 每次使用都要注册驱动 所以可以定义为静态代码块
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			System.out.println("注册驱动失败");
			e.printStackTrace();
		}
	}
	
//登入方法 返回Connection对象,连接数据库
	public static  Connection newInstance() throws SQLException {
		if (conne==null) {
			conne = DriverManager.getConnection(URL,USER,PAAWORD);
		}
		return conne;
	}
// 综合方法:传入 String 要执行的增删改
	public static int tool(String sql) {
		try {
			//执行SQL需要statement对象
			state = newInstance().createStatement();
			//执行sql语句,
			int rest = state.executeUpdate(sql);
			return rest;
		}catch (SQLException e) {
			e.printStackTrace();
		}finally {
			if(state!=null) {
				try {
					if(state!=null) {
						state.close();
					}
					if(conne!=null) {
						conne.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return 0;
	}

封装可以简化代码, 方便使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值