简洁版JDBCUtil工具类(基于反射)-实现简单CRUD操作

JDBCUtil工具类

1.  定义静态成员变量

 2. 静态代码块加载JDBCUtil资源(需要配置db.properties配置文件)

/**
	 * 加载JDBCUtil资源文件       
	 */
	static {
		try {
			InputStream inputStream=JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
			properties.load(inputStream);
			inputStream.close();
			Class.forName(properties.get("driverName").toString());
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

 3. 获取Connection连接对象

	/**
	 * 获取数据库连接对象
	 * @return
	 */
	public static Connection getConnect()
	{
		Connection connection=null;
		try {
			connection=DriverManager.getConnection(properties.getProperty("url"),
          properties.getProperty("user"),properties.getProperty("password"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}

4. 释放数据库连接对象资源

/**
	 * 释放资源
	 * @param resultSet
	 * @param preparedStatement
	 * @param connection
	 */
	
	public static void Close(ResultSet resultSet,PreparedStatement preparedStatement,Connection connection)
	{
		try {
			if(resultSet!=null)
			{
				resultSet.close();
			}
			if(preparedStatement!=null)
			{
				preparedStatement.close();
			}
			if(connection!=null)
			{
				connection.close();
			}
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

 5. 增删改操作

/**
	 * 增删改
	 * @param sql      Sql语句
	 * @param object    Sql参数
	 * @return
	 */
	public static int executeUpdateOrInsertOrDel(String sql,Object object [])
	{
		int result=-1;
		Connection connection=getConnect();
		PreparedStatement preparedStatement;
		try {
			
			preparedStatement=connection.prepareStatement(sql);
			if(object.length>0)
			{
				for(int i=0;i<object.length;i++)
				{
					preparedStatement.setObject(i+1, i);
				}
			}
			result=preparedStatement.executeUpdate();
			Close(null, preparedStatement, connection);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}	
		return result;
	}

6. 查询操作 (操作数据封装到List列表)

    /**
	 * 查询
	 * @param sql  Sql语句
	 * @param cla  封装数据类型
	 * @param objects  Sql语句参数
	 * @return
	 * @throws Exception
	 */
	public static List<Object> executeQuery(String sql,Class<?> cla,Object [] objects) throws Exception
	{
		List<Object> list=new ArrayList<>();
		
		Connection connection=getConnect();
		
		PreparedStatement preparedStatement=connection.prepareStatement(sql);
		
		if(objects.length>0)
		{
			for(int i=0;i<objects.length;i++)
			{
				preparedStatement.setObject(i+1, objects[i]);
			}
		}
		
		ResultSet resultSet=preparedStatement.executeQuery();
		
		Class<?> clz=Class.forName(cla.getName());
		while(resultSet.next())
		{
			Object bj=clz.newInstance();
			Field [] fdFields=clz.getDeclaredFields();
			
			for(Field f:fdFields)
			{
				f.setAccessible(true);
				
				String typeValue=f.getType().getName();
				
				Object beforeValue=resultSet.getObject(f.getName());
				
				Object afterValue=null;
				
				switch (typeValue) {
					case "int":
					case "java.lang.Integer":
						if(beforeValue!=null)
						{
							afterValue=Integer.parseInt(beforeValue.toString());
						}else {
							afterValue=0;
						}
						break;
					case "double":
					case "java.lang.Double":
						if(beforeValue!=null)
						{
							afterValue=Double.parseDouble(beforeValue.toString());
						}else {
							afterValue=0d;
						}
						break;
					case "float":
					case "java.lang.Float":
						if(beforeValue!=null)
						{
							afterValue=Float.parseFloat(beforeValue.toString());
						}else {
							afterValue=0f;
						}
	
					default:
						afterValue=beforeValue;
						break;
					}
				f.set(bj, afterValue);
				
				
			}
			list.add(bj);
		}
		Close(resultSet, preparedStatement, connection);
		return list;
	}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDBCUtil是一个用于管理JDBC连接的工具类。它可以帮助你轻松地创建、释放和管理数据库连接,同时也提供了一些方便的方法来执行SQL语句和获取结果集。 以下是一个JDBCUtil工具类的示例: ```java import java.sql.*; public class JDBCUtil { private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; public static Connection getConnection() { Connection conn = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } public static void release(Connection conn, Statement stmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void execute(String sql) { Connection conn = null; Statement stmt = null; try { conn = getConnection(); stmt = conn.createStatement(); stmt.execute(sql); } catch (SQLException e) { e.printStackTrace(); } finally { release(conn, stmt, null); } } public static ResultSet executeQuery(String sql) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } } ``` 这个工具类包含了以下几个方法: - `getConnection()`:获取数据库连接。 - `release(Connection conn, Statement stmt, ResultSet rs)`:释放数据库资源。 - `execute(String sql)`:执行SQL语句。 - `executeQuery(String sql)`:执行查询语句并返回结果集。 你可以通过以下方式来使用这个工具类: ```java public static void main(String[] args) { Connection conn = JDBCUtil.getConnection(); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM user"); while (rs.next()) { System.out.println(rs.getString("username")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtil.release(conn, stmt, rs); } } ``` 上面的代码中,我们首先使用`getConnection()`方法获取数据库连接,然后利用这个连接创建一个`Statement`对象并执行查询语句。最后,我们使用`release()`方法释放数据库资源。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值