Java Web笔记(五) - JDBC

本文介绍如何使用JDBC连接Oracle数据库,包括加载驱动、获取连接、执行SQL语句等步骤,并提供示例代码。还涉及调用存储过程、函数及处理图片数据的方法。

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

JDBC

Oracle驱动包

可以从Oracle安装路径下获取。

获取路径:D:\Oracle\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar

Java连接数据库过程

过程

1、加载驱动 ->对一个类(oracle.jdbc.driver.OracleDriver)进行类加载,获取类对象

    Class.forName("oracle.jdbc.driver.OracleDriver");

2、获取数据库连接

    url组成 : jdbc:oracle:thin:@ip:1521:xe/orcl

    DriverManager.getConnection(url , 数据库用户名, 数据库密码);

3、编写SQL语句 :例如select * from t_user ;

4、创建一个SQL执行器

    // 创建SQL执行器

    Statement statement =  conn.createStatement() ;

    或者

    // 创建SQL预编译执行器

5、执行SQL语句,并返回结果集

    ResultSet rs =  statement.executeQuery(sql);

6、遍历结果集

    while(rs.next()) {

        //获取结果集

        rs.getXXX("字段");

    }

7、关闭资源

代码示例:

try {
	// 1. 加载驱动
	Class.forName("oracle.jdbc.driver.OracleDriver");
	// 2. 获取数据库连接
	String url = "jdbc:oracle:thin:@localhost:1521:XE";
	Connection conn = DriverManager.getConnection(url, "shop", "shop");
	// 3. 编写SQL语句
	String sql = "select * from t_user";
	// 4. 创建一个SQL执行器
	Statement stat = conn.createStatement();
	// 5. 执行SQL语句,并返回结果集
	ResultSet rs = stat.executeQuery(sql);
	
	// 6. 遍历结果集
	while(rs.next()) {
		// 7. 获取记录内容
		int id = rs.getInt("ID");
		String name = rs.getString("NAME");
		String password = rs.getString("PASSWORD");
		System.out.println("id:" + id + ", name:" + name + ",password:" + password);
	}
	
	// 8. 关闭资源
	if(rs != null) {
		rs.close();
		rs = null;
	}
	if(stat != null) {
		stat.close();
		stat = null;
	}
	if(conn != null) {
		conn.close();
		conn = null;
	}
} catch (ClassNotFoundException e) {
	e.printStackTrace();
} catch (SQLException e) {
	e.printStackTrace();
}

调用存储过程

public UserInfo cunQian(Integer id, double money) throws Exception {
	// 连接数据库
	Connection conn = DBUtil.getConnection();
	// 创建存储过程预编译执行器
	CallableStatement cs = conn.prepareCall("{call cunqian(?, ?, ?)}");
	// 设置输入参数
	cs.setInt(1, id);
	// 设置输出参数的处理
	cs.registerOutParameter(2, Types.VARCHAR); // 第2个参数是数据类型
	// 设置输入输出参数的处理; 对输入输出的参数模式,先设值再注册数据类型
	cs.setDouble(3, money);
	cs.registerOutParameter(3, Types.DOUBLE);
	
	// 执行存储过程
	boolean b = cs.execute(); // 如果有结果集返回true, 否则返回false
	
	// 获取存储过程的执行结果
	String email = cs.getString(2);
	Double m = cs.getDouble(3);
	
	UserInfo userInfo = new UserInfo();
	userInfo.setEmail(email);
	userInfo.setMoney(m);
	
	DBUtil.close(null, cs, conn);
	return userInfo;
}

调用函数

public Double zhuanZhang(Integer id, Integer toId, double money)
		throws Exception {
	// 连接数据库
	Connection conn = DBUtil.getConnection();
	// 创建预编译执行器
	CallableStatement cs = conn.prepareCall("{? = call zhuanzhang(?, ?, ?)}");
	// 设置输入参数
	cs.registerOutParameter(1, Types.DOUBLE);
	cs.setInt(2, id);
	cs.setInt(3, toId);
	// 设置输入输出参数的处理; 对输入输出的参数模式,先设值再注册数据类型
	cs.setDouble(4, money);
	cs.registerOutParameter(4, Types.DOUBLE);
	
	// 执行函数
	boolean b = cs.execute(); // 如果有结果集返回true, 否则返回false
	
	// 获取存储过程的执行结果
	Double m = cs.getDouble(1);
	
	DBUtil.close(null, cs, conn);
	return m;
}

将图片保存到数据库

数据库表中图片字段的数据类型:blob

Java实体中图片变量的数据类型:byte[]

示例:

测试用例:

public static void testSaveImg() throws Exception {
	UserInfo userInfo = new UserInfo();
	userInfo.setId(3);
	userInfo.setTel("55555555");
	userInfo.setEmail("lisi@qq.com");
	userInfo.setIdCard("266-18");
	userInfo.setUserId(1);
	userInfo.setMoney(2000.2);
	
	// 将图片转成字节数组
	File file = new File("C:\\Users\\Administrator\\Desktop\\作业.bmp");
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	FileInputStream fis = new FileInputStream(file);
	byte[] buf  = new byte[1024];
	int len = -1;
	while((len = fis.read(buf)) != -1) {
		bos.write(buf, 0, len);
	}
	userInfo.setImg(bos.toByteArray()); // 获取图片的字节数组
	int n = dao.saveImg(userInfo);
	System.out.println(n);
}

数据库操作:

public int saveImg(UserInfo userInfo) throws Exception {
	// 连接数据库
	Connection conn = DBUtil.getConnection();
	// 拼接SQL语句
	String sql = "insert into t_user_info(id, tel, email, idcard, userId, money, img) values(?, ?, ?, ?, ?, ?, ?)";
	// 创建SQL预编译执行器
	PreparedStatement pstat = conn.prepareStatement(sql);
	// 设置值
	pstat.setInt(1, userInfo.getId());
	pstat.setString(2, userInfo.getTel());
	pstat.setString(3, userInfo.getEmail());
	pstat.setString(4, userInfo.getIdCard());
	pstat.setInt(5, userInfo.getUserId());
	pstat.setDouble(6, userInfo.getMoney());
	pstat.setBytes(7, userInfo.getImg());
	// 执行SQL语句,并返回结果
	int executeUpdate = pstat.executeUpdate();
	// 关闭资源
	DBUtil.close(null, pstat, conn);
	return executeUpdate;
}

事务

Connection conn = DBUtils.getConnection(); // 获取数据库连接

conn.setAutoCommit(false); // 开启事务

代码...

conn.commit(); // 提交事务

conn.rollback(); // 回滚事务

注意,以下使用数据库为sql2000,驱动jtds1.2.2 一、调用存储过程(无结果集返回) Connection connection = ConnectionHelper.getConnection(); CallableStatement callableStatement = connection.prepareCall("{ call procedureName(?,?) }"); callableStatement.setString(1, "xxxxxxxx"); callableStatement.setString(2, "xxxxxxxx"); callableStatement.execute(); //获得sql的消息并输出,这个估计很多人都需要 SQLWarning sqlWarning = callableStatement.getWarnings(); while (sqlWarning != null) { System.out.println("sqlWarning.getErrorCode() = " + sqlWarning.getErrorCode()); System.out.println("sqlWarning.getSQLState() = " + sqlWarning.getSQLState()); System.out.println("sqlWarning.getMessage() = " + sqlWarning.getMessage()); sqlWarning = sqlWarning.getNextWarning(); } //close ConnectionHelper.closeConnection(callableStatement, connection); 二、调用存储过程,返回sql类型数据(非记录集) Connection connection = ConnectionHelper.getConnection(); CallableStatement callableStatement = connection.prepareCall("{ call procedureName(?,?,?) }"); callableStatement.setString(1, "xxxxxxxx"); callableStatement.setString(2, "xxxxxxxx"); //重点是这句1 callableStatement.registerOutParameter(3, Types.INTEGER); callableStatement.execute(); //取返回结果,重点是这句2 //int rsCount = callableStatement.getInt(3); //close ConnectionHelper.closeConnection(callableStatement, connection); 三、重点来了,返回记录集,多记录集 注意,不需要注册返回结果参数,只需要在sql中select出结果即可 例如:select * from tableName 即可得到返回结果 Connection connection = ConnectionHelper.getConnection(); CallableStatement callableStatement = connection.prepareCall("{ call procedureName(?) }"); //此处参数与结果集返回没有关系 callableStatement.setString(1, "xxxxxxxx"); callableStatement.execute(); ResultSet resultSet = callableStatement.getResultSet(); //以上两个语句,可以使用ResultSet resultSet = callableStatement.executeQuery();替代 //多结果返回 ResultSet resultSet2; if (callableStatement.getMoreResults()) { resultSet2 = callableStatement.getResultSet(); while (resultSet2.next()) { } } //close ConnectionHelper.closeConnection(callableStatement, connection); 提示:多结果返回可以使用如下代码(以上主要让大家明白,单一结果和多结果的区别): Boolean hasMoreResult = true; while (hasMoreResult) { ResultSet resultSet = callableStatement.getResultSet(); while (resultSet.next()) { } hasMoreResult = callableStatement.getMoreResults(); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值