import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @Title: JDBCUtils.java * @Description: * @author zhangkai * @date 2020年4月3日上午9:56:32 * @see [相关类/方法] * @since [产品/模块版本] */ @Component public class JDBCUtils { private static String user; private static String password; private static String url; private static String driver; /** * 功能:用于获取连接 * * @return Connection连接对象 @ throws Exception * */ public Connection getConnection() { // 获取连接 try { Class.forName(driver); return DriverManager.getConnection(url, user, password); } catch (Exception e) { throw new RuntimeException(e); } } /** * 功能:释放资源 通用的释放资源方法,无用参数留null * * @param connection * @param statement * PreparedStatement是其子类,使用多态,也可引用 * @param resultSet */ public void close(Connection connection, Statement statement, ResultSet resultSet) { // 使用try-catch方式处理异常,免去调用者再次处理 try { if (connection != null) { connection.close(); } if (statement != null) { statement.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { // 编译时异常转为运行时异常 throw new RuntimeException(e); } } public int toUpdateDelStatus(String tableName) throws Exception { Connection connection = null; Statement statement = null; int i = 0; try { String sql = "UPDATE " + tableName + " SET del_status = '1' "; connection = this.getConnection(); statement = connection.createStatement(); i = statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { this.close(connection, statement, null); return i; } } @Value("${spring.datasource.master.username}") public void setUser(String users) { user = users; } @Value("${spring.datasource.master.username}") public void setPassword(String passwords) { password = passwords; } @Value("${spring.datasource.master.jdbc-url}") public void setUrl(String urls) { url = urls; } @Value("${spring.datasource.master.driver-class-name}") public void setDriver(String drivers) { driver = drivers; } }
需要注意 :
1>类上面需要@component
2>需要编写set 方法
查考文章:https://blog.csdn.net/mononoke111/article/details/81088472#commentBox