JDBC连接抽象方法的使用例子

网友投稿 545 2022-10-28

JDBC连接抽象方法的使用例子

JDBC连接抽象方法的使用例子

package com.zdlt.auth.api.base.datasource;import java.sql.*;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;/** * BaseDataSource *

* Created by shiyanjun on 2019/12/19. */public abstract class BaseDataSource { /** * 获取连接 * * @return */ abstract Connection getConnection() throws SQLException; /** * 执行查询 * * @param sql * @return * @throws SQLException */ public List> query(String sql) throws SQLException { Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); return resoleResult(resultSet); } /** * 解析结果 * * @param resultSet * @return */ public List> resoleResult(ResultSet resultSet) throws SQLException { List> resultList = new ArrayList<>(); ResultSetMetaData metaData = resultSet.getMetaData(); while (resultSet.next()) { Map resultMap = new LinkedHashMap<>(); for (int i = 1; i <= metaData.getColumnCount(); i++) { String columnLabel = metaData.getColumnLabel(i); String columnValue = resultSet.getString(columnLabel); resultMap.put(columnLabel, columnValue); } resultList.add(resultMap); } return resultList; }}

package com.zdlt.auth.api.base.datasource;import java.sql.Connection;import java.sql.SQLException;/** * CustomDataSource *

* Created by shiyanjun on 2019/12/19. */public class CustomDataSource extends BaseDataSource { private String url; private String username; private String password; CustomDataSource(String url, String username, String password) { this.url = url; this.username = username; this.password = password; } /** * 获取连接 * * @return */ @Override public Connection getConnection() throws SQLException { return ConnectUtil.getConnection(url, username, password); }}

package com.zdlt.auth.api.base.datasource;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;/** * ConnectUtil *

* Created by shiyanjun on 2019/12/19. */public class ConnectUtil { /** * 获取JDBC连接 * * @param url * @param username * @param password * @return * @throws SQLException */ public static Connection getConnection(String url, String username, String password) throws SQLException { return DriverManager.getConnection(url, username, password); }}

package com.zdlt.auth.api.base.datasource;import java.sql.SQLException;import java.util.List;import java.util.Map;public class App { public static void main(String[] args) { CustomDataSource customDataSource = new CustomDataSource( "jdbc:mysql://127.0.0.1:3306/authapi", "root", "123456"); try { List> resultList = customDataSource.query("select * from auth_code"); System.out.println(resultList); } catch (SQLException e) { e.printStackTrace(); } }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:带你手写一个数据库连接池
下一篇:OpenCensus统计信息收集和分布式追踪框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~