3、为了使JDBC用起来更加的方便,进行MyJDBCUtils的包装

1、为了使JDBC用起来更加的方便,进行MyJDBCUtils的包装,利用MyJDBCUtils对外提供,操作数据的方法

2、MyJDBCUtils的代码如下

     

package com.jdbc.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MyJDBCUtils {

	static String url = "jdbc:mysql://localhost:3306/testdatabase";
	static String username = "root";
	static String password = "1234";

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			throw new RuntimeException("获取连接Mysql数据库连接失败");
		}
		return conn;
	}

	public static void release(Connection conn, Statement st, ResultSet rs) {

		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				throw new RuntimeException("ResultSet关闭异常");
			}
			rs = null;
		}
		if (st != null) {
			try {
				st.close();
			} catch (Exception e) {
				throw new RuntimeException("Statement关闭异常");
			}
			st = null;
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				throw new RuntimeException("Connection关闭异常");
			}
			conn = null;
		}

	}

}
3、使用MyJDBCUtils进行Mysql的访问代码如下

package com.jdbc.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

public class TestMyJDBCUtils {

	@Test
	public void testMyJDBCUtils() {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = MyJDBCUtils.getConnection();
			st = conn.createStatement();
			rs = st.executeQuery("select * from user  ");

			while (rs.next()) {
				int id = rs.getInt(rs.findColumn("id"));
				String uname = rs.getString(rs.findColumn("uname"));
				int age = rs.getInt(rs.findColumn("age"));
				// 遍历输出
				System.out.println("id " + id + " " + "uname " + uname + " "
						+ "age " + age + " ");
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			// 释放资源
			MyJDBCUtils.release(conn, st, rs);
		}
	}
}


4、程序的访问结果




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值